【发布时间】:2021-11-20 04:40:31
【问题描述】:
我正在尝试将一组 id 从 C# 中的 mongodb 加载到列表中。任何人都可以帮助建议任何 mongodb 的收集或过滤方法吗?我对此很陌生
【问题讨论】:
-
请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。
标签: c# mongodb mongodb-.net-driver
我正在尝试将一组 id 从 C# 中的 mongodb 加载到列表中。任何人都可以帮助建议任何 mongodb 的收集或过滤方法吗?我对此很陌生
【问题讨论】:
标签: c# mongodb mongodb-.net-driver
假设你有一个类似这样的模型:
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();
【讨论】:
除了@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()
【讨论】: