gpt4 book ai didi

C# MongoDB LINQ : Cannot query nested list

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

我正在尝试使用官方 C# 驱动程序查询 MongoDB 集合。这是我创建的对象结构:

IMongoDatabase db = mongoClient.GetDatabase("appdb");
IMongoCollection<MusicFile> musicfiles = db.GetCollection<MusicFile>("files");

public class MusicFile
{
public ObjectId Id { get; set; }

public string Name { get; set; }

public IList<Comment> Comments { get; set; }
}

public class Comment
{
public string Text { get; set; }
}

这是我试图获取任何 MusicFile 对象的查询,该对象包含具有属性 Text = "Comment1"的 Comment 对象:

musicfiles.AsQueryable().Where(f => f.Comments != null && f.Comments.Any(c => c.Text == "Comment1")).ToList();

我无法让这个查询工作,它总是返回一个空列表。我也试过这个,但也没用:

musicfiles.Find(f => f.Comments.Any(c => c.Text == "Comment1")).ToList()

但是,如果我得到完整的集合是内存,则查询有效:

musicfiles.Find(FilterDefinition<MusicFile>.Empty).ToList().Where(f => f.Comments != null && f.Comments.Any(c => c.Text == "Comment1")).ToList();

这似乎是一种非常低效的查询方式。有什么建议吗?

最佳答案

好的。我回到家了。试试这个:

var musicFilter = Builders<MusicFile>.Filter;
var commentFilter = Builders<Comment>.Filter;

var files = musicfiles
.Find(
musicFilter.NE(m => m.Comments, null)
& musicFilter.ElemMatch(m => m.Comments, commentFilter.Eq(c => c.Text, "Comment1"))
)
.ToEnumerable()
.ToList();

请注意,我调用 .ToList() 是因为,否则,如果您多次遍历文件,您将多次调用相同对象的数据库。

关于C# MongoDB LINQ : Cannot query nested list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42731755/

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