Home > Net >  How to load multiple documents based on ids?
How to load multiple documents based on ids?

Time:09-29

I'm trying to load a set of ids from mongodb in C# to a list. Can anyone help to suggest any collection or filter method of mongodb? I'm very new to this

CodePudding user response:

Assuming you have a model something like this:

public class MyModel
{
    [BsonId]
    public ObjectId Id {get;set;}
}

You can use In:

List<ObjectId> documentsToLoad = getDocumentsToLoad();

List<MyModel> documents = await myCollection
    .Find(
        Builders<MyModel>.Filter.In(m => m.Id, documentsToLoad)
    )
    .ToListAsync();

Alternatively, if you're just getting the "raw" BsonDocument objects you can write:

List<BsonDocument> documents = await myCollection
    .Find(
        Builders<BsonDocment>.Filter.In("_id", documentsToLoad)
    )
    .ToListAsync();

CodePudding user response:

In addition to the answer of @Llama, you can also use Expression to achieve the same result.

var documentIds = GetDocumentIds();
var documents = await mongoContext
    .GetCollection<MyModel>("collectionName")
    .Find(model => documentIds.Contains(model.Id))
    .ToListAsync();

You can also use the Linq extensions from MongoDB.Driver.Linq namespace.

var documents = await mongoContext
    .GetCollection<MyModel>("collectionName")
    .AsQueryable()
    .Where(model => documentIds.Contains(model.Id))
    .ToListAsync()
  • Related