Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB in C# - Type not null query

Tags:

c#

mongodb

I have collection where each document has two fields:

  1. "Field1" - string value
  2. "Field2" - object value with "Field2.Field3(object).Field4(string)".

Now I'm trying to take all documents for which "Field2.Field3" is not null. When I do sth like this for Field1 then it works:

query = Builders<MyDocument>.Filter.Ne(t => t.Field1, null)

However, when I do the same but for "Field2.Field3":

query = Builders<MyDocument>.Filter.Ne(t => t.Field2.Field3, null)

then I got an error "command find failed". Where is the problem?

like image 369
jujus Avatar asked Jun 04 '26 07:06

jujus


1 Answers

Try this

query = Builders<MyDocument>.Filter.Ne(t => t.Field2.Field3, (BsonNull)null)

Or this

query = Builders<MyDocument>.Filter.Ne("Field2.Field3", (BsonNull)null)

Also make sure MyDocuments contains the class that have field3 in the properties

I can't tell for sure why this works but it worked for me.

It's a guess but with the method aways expect a value so this casting is a workaround.

If I find the real explanation, I'll share here.

like image 159
Victor Adalto Avatar answered Jun 06 '26 07:06

Victor Adalto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!