简体   繁体   English

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

[英]Find all MongoDB documents from a list of ObjectIDs

I am trying to find all documents from a MongoDB database, which has the ObjectID from my list of IDs with C#. 我正在尝试从MongoDB数据库中查找所有文档,该数据库在我的C#ID列表中具有ObjectID。 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 is simply a list of ObjectIDs from the MongoDB database. productIDs只是MongoDB数据库中ObjectID的列表。 Obviously trying to find by a list of IDs doesn't work that way, as it takes a single parameter. 显然,尝试通过ID列表进行查找并不可行,因为它需要一个参数。

How do I .Find() all the documents from my list of product IDs? 如何从产品ID列表中查找.Find()所有文档?

This is the strongly-typed way. 这是强类型的方式。

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;
}

I figured out a pretty hacky solution. 我想出了一个不错的解决方案。 Not one of my proudest moments to be honest: 老实说,我并不是最骄傲的时刻之一:

ObjectId[] allIDs = new ObjectId[productIDs.Count];

for(var i = 0; i < productIDs.Count; i++)
{
    allIDs[i] = new ObjectId(productIDs[i]);
}

var filter = new BsonDocument("_id", new BsonDocument("$in", new BsonArray(allIDs)));
var products = db.GetCollection<Product>("Products").Find(filter).ToEnumerable();

But hey, it works . 但是, 它有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM