Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Field Equals Null in MongoDb C# Driver 2.0

Tags:

c#

mongodb

I have a very simple query for mongo:

db.items.find( { MyFieldName: { $exists: true, $eq: null } } );

Not that it needs to be explained, but it finds documents which have a MyFieldName and where the value of that field is null. It seems like this would be really simple to do with the C# driver:

var fieldExistsFilter= Builders<BsonDocument>.Filter.Exists("MyFieldName", true);
var fieldValueIsNullFilter = Builders<BsonDocument>.Filter.Eq("MyFieldName", null); 

However the second filter, fieldValueIsNullFilter, does not build if I try to check for null. It works fine if I write "testString" or anything like that, but not with null.

tl:dr; version: How do I create a filter to check if field is null in MongoDb C# driver?

Note, I checked other answers and they recommend $exists does what I want - it does not, as per mongo docs:

When is true, $exists matches the documents that contain the field, including documents where the field value is null. If is false, the query returns only the documents that do not contain the field.

like image 700
VSO Avatar asked Jun 14 '16 14:06

VSO


1 Answers

In addition to the comment above you can write like this if you have some entity (depends on the property type):

public class CustomEntity
{
    public string Id { get; set; }

    public string StringProperty { get; set; }

    public DateTime? DateTimeProperty { get; set; }
}


var filterIfStringPropertyNull = Builders<CustomEntity>.Filter.Eq(o => o.StringProperty, null); // if property is string

var filterIfDatePropertyNull = Builders<CustomEntity>.Filter.Eq(o => o.DateTimeProperty, BsonNull.Value.ToNullableUniversalTime());  // if property is DateTime?

And so on. It could be easier

like image 141
Mike Polo Avatar answered Sep 28 '22 22:09

Mike Polo