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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With