MongoDB - Filter data matching one of the options

57 Views Asked by At

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.

1

There are 1 best solutions below

4
On BEST ANSWER

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" }) },
    }}
};