gpt4 book ai didi

c# - MongoDB C# 从 ID 列表中获取所有文档

转载 作者:IT老高 更新时间:2023-10-28 13:18:57 25 4
gpt4 key购买 nike

我有一个 ID 列表

List<string> Ids;

我想检索与这些 ID 匹配的所有文档。

网上有解决办法:

var ids = new int[] {1, 2, 3, 4, 5};
var query = Query.In("name", BsonArray.Create(ids));
var items = collection.Find(query);

但它们都使用旧的 C# 驱动程序和(不再那么新的)2.2.4 驱动程序,API 已更改,我找不到如何构建此查询。

最佳答案

请看下面的片段(使用 LINQPad 制作)

void Main()
{
// To directly connect to a single MongoDB server
// or use a connection string
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");


var collectionEmpInfo = database.GetCollection<Employee>("Employee");
Employee EmpInfo = new Employee
{

EmpID = "103",
EmpName = "John",
CreatedAt = DateTime.Now,
EmpMobile = new List<Mobile>
{
new Mobile{ MobNumber = "55566610", IsPreferred = true, MobID = ObjectId.GenerateNewId() },
new Mobile{ MobNumber = "55566611", IsPreferred = false, MobID = ObjectId.GenerateNewId() },
}
};
//collectionEmpInfo.InsertOne(EmpInfo);

var filterDef = new FilterDefinitionBuilder<Employee>();
var filter = filterDef.In(x=>x.EmpID , new[]{"101","102"});
filter.Dump();
var empList = collectionEmpInfo.Find(filter).ToList();
empList.Dump();
}
public class Employee
{
public ObjectId Id { get; set; }
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
public DateTime CreatedAt { get; set; }
}

public class Mobile
{
public ObjectId MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
}

和结果截图

linquPaDscreenShot

关于c# - MongoDB C# 从 ID 列表中获取所有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37789224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com