1

I'm trying to filter MongoDB data using a query written using a BsonDocument where a parameter - eg "name" - equals one of an array of possible values, but can't get the correct syntax for this:

Eg "name" equals "bill" or "name" equals "fred"

I've tried using the format:

query = new BsonDocument
    {
        {"name" , new BsonDocument {
            { "$eq" , "bill"},
            { "$eq" , "fred"}
        }}
    };

var entities = await collection.Find(query).ToListAsync();

But I get the error:

System.InvalidOperationException: 'Duplicate element name '$eq'.'

I'm sure the answer is pretty simple, but can't quite nail it.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Mr Fivian
  • 53
  • 3

1 Answers1

1

For your scenario which matches any of the parsed names, you should apply the $in operator and provide a list/array.

query = new BsonDocument
{
    { "name", new BsonDocument {
        { "$in", BsonArray.Create(new List<string> { "bill", "free" }) },
    }}
};
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • Thanks for your promp reply Yong, but still having problems. BsonDocument query = new BsonDocument { { "name" , new BsonDocument { { "$eq", "bill"}, } } }; works , but BsonDocument query4 = new BsonDocument { { "name" , new BsonDocument { { "$eq", BsonArray.Create(new List { "bill" }) } } } }; returns 0 – Mr Fivian Jun 06 '23 at 09:12
  • Sorry, not sure how to correctly format comment! – Mr Fivian Jun 06 '23 at 09:15
  • Use `$in` but not `$eq`. As you are checking whether the name is within the parsed array value, but when you use `$eq`, it compares the `name` is equivalent to `[ "bill" ]`. – Yong Shun Jun 06 '23 at 09:19
  • Of course!! Many thanks Yong. You are a star. :-) – Mr Fivian Jun 06 '23 at 09:54