'How to build filter on multiple values of same attribute in C# with MongoDb driver

I am trying to create a filter on a certain attribute in my MongoDB table. I have an array of values, and I want to retrieve only results from the MongoDB that contain that value for the attribute I'm searching on.

For example:

I want to search for all of the following Ids: "12345", "23456", "34567" I have an array of these values:

var ids = ["12345", "23456", "34567"]

The filter I have currently built looks like this:

var builder = Builders<Common.Models.ServiceRequest>.Filter;
FilterDefinition<Common.Models.ServiceRequest> filter = builder.Empty;
filter = builder.Ne(x => x.Id, null);
foreach (string id in ids)
{
    filter = filter | builder.Eq(x => x.Id, id);
}

this for some reason does not seem to work, even though I am using the or(|) in MongoDriver.

Any guidance on this would be appreciated! Thanks



Solution 1:[1]

You should use the In operator to compare with a collection or array of values.

var ids = ["12345", "23456", "34567"];

var builder = Builders<Common.Models.ServiceRequest>.Filter;
FilterDefinition<Common.Models.ServiceRequest> filter = builder.Empty;
filter = builder.Ne(x => x.Id, null);
builder.In(x => x.Id, ids);

The In filter takes an IEnumerable so you can use it directly with lists, arrays or any other enumerable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fbiagi