Find all MongoDB documents from a list of ids using `in` operator

Viewed 1046

i am trying to find documents in collection by ids. Most of the suggested answers use C# class that matches with the document. something like here

var filter = Builders<Product>.Filter
    .In(p => p.Id, productObjectIDs);

i don't have corresponding C# class, so i am using BsonDocument

public async Task<IEnumerable<BsonDocument>> GetData(IEnumerable<int> documentIds)
{
    var collection = _mongoDatabase.GetCollection<BsonDocument>("mycollection");

    // how do set filter here
    var filterBuilder = Builders<BsonDocument>.Filter.In<int>("???????", documentIds);

    var projection = Builders<BsonDocument>.Projection
       .Include("_id")
       .Include("status")
       .Include("units");

    var result = await collection.Find(filterBuilder).Project<BsonDocument>(projection).ToListAsync().ConfigureAwait(false);
    return result;
}

I am not sure how do i set filter with in operator?

1 Answers

You may try this filter:

var filter = new BsonDocument("_id", new BsonDocument("$in", new BsonArray(documetIds)));

Based on this answer

Related