useruser00
useruser00

Reputation: 189

How to query field equals empty array?

I have an array field in my collection which have value with properties or empty value as "[]"

For fetching the documents having empty "[]" value in mongodb i use

db.getCollection('collection').find({"ArrayFieldName":{$eq:[]}})

This gives me result as expected. But when i try to form this query in the C# using mongodb driver i couldnt get the expected Result.

I tried, filterBuilder.Eq("ArraryFieldName", "[]") and filterBuilder.Eq("ArraryFieldName", new ArraryClassName(){})

Need help with C# filter builder to specify $eq:[] for arrary field.

Upvotes: 1

Views: 1469

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38785

An instance of ArraryClassName clearly won't work because it's not an array instance - it's a single object. Likewise "[]" won't work because it's a string.

You can check directly translate your CLI query to this filter:

Builders<BsonDocument>.Filter.Eq<BsonArray>("ArraryFieldName", new BsonArray())

Though if you simply want to check that the existing array is empty, you can use this filter instead:

Builders<BsonDocument>.Filter.Size("ArraryFieldName", 0)

P.S. I would strongly suggest using C# data models as it makes everything much easier to work with.

Also, you have called your field ArraryFieldName (notice the extra r at the end of Array). If you don't have existing data with this misspelled property name, you might want to correct the spelling.

Upvotes: 4

Related Questions