gpt4 book ai didi

c# - 使用 LINQ/C# 在 MongoDB 集合中定位子对象

转载 作者:可可西里 更新时间:2023-11-01 10:24:45 25 4
gpt4 key购买 nike

我正在尝试编写一段代码,使用 Linq 在 MongoDB 集合中查找对象。这是我的代码:

 class Program
{
static void Main(string[] args)
{
var client = new MongoClient();
var db = client.GetDatabase("SoundsDB");
var collection = db.GetCollection<Sound>("SoundsCollection");
string myID = "0vvyXSoSHI";

var myObjects = collection
.Find(b => b.objectId == myID);

}
}

public class Sound
{
public string _id { get; set; }
public Result[] results { get; set; }
}

public class Result
{
public Audio_File audio_file { get; set; }
public DateTime createdAt { get; set; }
public string location { get; set; }
public string objectId { get; set; }
public DateTime updatedAt { get; set; }
}

public class Audio_File
{
public string __type { get; set; }
public string name { get; set; }
public string url { get; set; }
}

这是我的 MongoDB 集合中的 JSON:

{
"_id" : ObjectId("56acced71b8ac8702446e8c6"),
"results" : [
{
"audio_file" : {
"__type" : "File",
"name" : "tfss-3c489351-0338-4903-8d94-a0f0c7091ef9-hi.m4a",
"url" : "http://files.parsetfss.com/hithere.m4a"
},
"createdAt" : "2014-12-27T22:59:04.349Z",
"location" : "Home",
"objectId" : "0vvyXSoSHI",
"updatedAt" : "2015-02-26T22:48:02.264Z"
}
]

我正在尝试让它工作,但在以下行中:

                .Find(b => b.objectId == myID)

我得到这个错误:无法将 lambda 表达式转换为类型“MongoDB.Driver.FilterDefinition”,因为它不是委托(delegate)类型

知道如何修复它并能够使用对象的 objectId 在 JSON 中搜索对象吗?谢谢!

最佳答案

我认为问题在于您正在搜索子文档,而不是主文档。试试这个:

var myObjects = collection
.Find(b => b.results.Any(r=>r.objectId == myID));

此外 - 确保 objectId 值实际上是您集合中的一个字符串。它似乎是对象模型中的一个字符串,但在数据库中是一个 objectId。您可能需要 (a) 更改您的对象模型和 (b) 更改该查询,以便您要求 r.objectId == ObjectId.Parse(myID)而不是我写的方式。

c# MongoDb .Find 是异步的

如果您使用的是 C# 驱动程序,您可能还需要为此调用实现异步:

static void Main() {
MainAsync().Wait();
}

static async Task MainAsync() {

var client = new MongoClient();
var db = client.GetDatabase("SoundsDB");
var collection = db.GetCollection<Sound>("SoundsCollection");
string myID = "0vvyXSoSHI";

var myObjects = await collection
.Find(b => b.objectId == myID).ToListAsync();

}

这样,您将使用查找,并将结果转换为列表(因此,myObjects 将是一个 List<SoundsCollection> 对象)。

关于c# - 使用 LINQ/C# 在 MongoDB 集合中定位子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35106558/

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