1

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.

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This worked Filter.Eq<BsonArray>("ArraryFieldName", new BsonArray())... I tried with Model class previously, but it not giving required value "[]" instead it coming with property names with default values.... BsonArray provided required output
You can still use string property names if needed (it's not obvious but it works), but with a model you can use something like model => model.ArrayFieldName, if that array field exists in your model object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.