[英]C# MongoDB LINQ: Cannot query nested list
我正在嘗試使用官方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()是因為,否則,如果您多次遍歷文件,則將為同一對象獲得對數據庫的多次調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.