How to select documents by field range of values in MongoDB C# driver?

3.2k views Asked by At

I have a collection named Items. Documents in the Items collection have a field named "LocationId." How do I select, and bring back to server, all Item documents that have a LocationId that matches a list, array, etc (whatever collection you prefer) of Location Ids?

tl:dr for clarity:
1. Have Items collection.
2. Have list of LocationIds, e.g. "1, 5, 6, 12, 99" on the server.
3. Need to bring back all Item documents that have a LocationId listed in the collection.

3

There are 3 answers

4
rnofenko On BEST ANSWER

You can build simple queries using lambda expression, MongoDB.Driver supports it

var collection = database.GetCollection<Item>("Item");
var list = await collection.Find(x => locationIds.Contains(x.LocationId)).ToListAsync();
0
VSO On

I was given this solution, which works with the older driver:

 var locations = new BsonValue[] { 1, 2, 3, 4 };
 var collection = database.GetCollection<Item>("Item");
 var data = collection
            .Find(Builders<BsonDocument>.Filter.In("LocationId", locations))
            .Project(x => Mapper.Map<BsonDocument, ItemViewModel>(x))
            .ToListAsync().Result;

The funny thing is that I don't know what "new BsonValue[]{}" does. Guess is bson array.

0
kennydust On

here's an alternate way using builders/filters.

var ids = new List<Int32> { 1, 2, 3, 4, 5, 6 };
var filter = Builders<Item>.Filter.AnyIn("LocationId", ids);
var collection = database.GetCollection<Item>("Item");
var results = await collection.FindAsync(filter);

var locations = await results.ToListAsync();