【问题标题】:How to load multiple documents based on ids?如何根据 id 加载多个文档?
【发布时间】:2021-11-20 04:40:31
【问题描述】:

我正在尝试将一组 id 从 C# 中的 mongodb 加载到列表中。任何人都可以帮助建议任何 mongodb 的收集或过滤方法吗?我对此很陌生

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: c# mongodb mongodb-.net-driver


【解决方案1】:

假设你有一个类似这样的模型:

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

你可以使用In:

List<ObjectId> documentsToLoad = getDocumentsToLoad();

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

或者,如果您只是获取“原始” BsonDocument 对象,您可以编写:

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

【讨论】:

  • 我认为你的答案会比上面的亚历山德拉更有效?我觉得你的答案会更快,因为它使用 Mongo 的 Filter.In 语法而不是标准的 C# .Contains
  • @walnut_salami 我在这里不是 100% 确定的,但我认为它们可能被翻译成有效的相同的东西。不过,我不确定进行这种转换的效率。
【解决方案2】:

除了@Llama的回答,你也可以使用Expression达到同样的效果。

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

您还可以使用来自MongoDB.Driver.Linq 命名空间的Linq 扩展。

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

【讨论】:

    猜你喜欢
    • 2021-01-16
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2020-10-28
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多