从ObjectID列表中查找所有MongoDB文档

从ObjectID列表中查找所有MongoDB文档

问题描述:

我正在尝试从MongoDB数据库中查找所有文档,该数据库在我的C#ID列表中具有ObjectID.这是我正在尝试的:

I am trying to find all documents from a MongoDB database, which has the ObjectID from my list of IDs with C#. Here's what I'm trying:

public IEnumerable<Product> GetFromIDs(List<string> productIDs)
{
    var client = new MongoClient(new MongoUrl("mongodb://localhost:27017"));
    var db = client.GetDatabase("Database");
    var products = db.GetCollection<Product>("Products")
        .Find(x => x._id == productIDs)
        .ToEnumerable();
    return products;
}

productIDs只是MongoDB数据库中的ObjectID列表.显然,尝试通过ID列表进行查找并不可行,因为它需要一个参数.

productIDs is simply a list of ObjectIDs from the MongoDB database. Obviously trying to find by a list of IDs doesn't work that way, as it takes a single parameter.

如何.Find()产品ID列表中的所有文档?

How do I .Find() all the documents from my list of product IDs?

这是强类型方法.

public IEnumerable<Product> GetFromIDs(List<string> productIDs)
{
    var client = new MongoClient(new MongoUrl("mongodb://localhost:27017"));
    var db = client.GetDatabase("Database");
    var productsCollection = db.GetCollection<Product>("Products");

    var productObjectIDs = productIDs.Select(id => new ObjectId(id));

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

    var products = productsCollection
        .Find(filter)
        .ToEnumerable();

    return products;
}