Mongo DB driver fails to serialize match query if one of arguments is null

28 views
Skip to first unread message

Yura Dubenskyy

unread,
Nov 16, 2017, 11:06:07 AM11/16/17
to mongodb-user
I get NullReferenceException when running next simple query:

int? currentUserId = null;
_client.GetDatabase("mydatabase").GetCollection<MyDocument>("mycollection").Aggregate().Match(m => m.CustomerId == currentUserId && m.Participants.Any(x => x.CustomerId == currentUserId)).FirstOrDefault();

When I initialize "currentUserId " with value, it runs fine.

In my example MyDocument.CustomerId is Nullable<int> and property on inned collection Participant.CustomerId  is int.

Looks like it depends on type of property of document. 
If property is non-nullable (i.e. int) but variable in expression is nullable (currentUserId in this example) - than it tries to get value from variable no matter what.

Also, looks like queries are not getting evaluated and simplified before being serialized. Consider this example:

int? currentUserId = null;
_client.GetDatabase("mydatabase").GetCollection<MyDocument>("mycollection").Aggregate()Match(m => currentUserId != null && m.CustomerId == currentUserId && m.Participants.Any(x => x.CustomerId == currentUserId)).FirstOrDefault();

If currentUserId is null (which is known at the time of traversing expression tree), than whole condition will be evaluated to false no matter what go after (because of and && operation used). So in such case query can be first simplified to simple (m => false) and then serialized.

Wan Bachtiar

unread,
Dec 22, 2017, 2:00:00 AM12/22/17
to mongodb-user

Also, looks like queries are not getting evaluated and simplified before being serialized. Consider this example:

Hi Yura,

It’s been a while since you posted this question, have you found a solution yet ?

You may have to represent the null as BsonNull.Value.
If you still have further question on this, could you please provide:

  • MongoDB C# driver version
  • Example code class mapping
  • Example documents

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages