Mongodb C# 查找异步。使用linq过滤文档内的列表

Mongodb C# FindAsync. Filter on list inside document using linq

我有一个 mongodb,我想过滤文档列表中的值。

我的文档看起来像这样:

{"_id": "guid" , "mylist": {"stuff": "a", "morestuff": "b"} }

我想通过在 FindAsync 方法中使用 linq 表达式找到一个文档,其中 "mylist" 中的 "stuff" 是 "a"。

到目前为止我的最大努力:

collection.FindAsync(item => item.mylist.Where(item2 => item2.stuff == "a") )

不幸的是,C# 不接受这个声明,我收到以下错误:

Cannot implicitly convert type "System.Collections.Generic.IEnumerable" to "bool"

Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type"

我对 linq 比较陌生,大部分时间都在使用 resharper 为我做这些,所以我可能在这里遗漏了一些非常基本的东西。

抱歉,我误解了你的问题,你应该用 Any 替换 Where (它给你传递给你的表达式的项目的集合),如果有任何项目在该表达式的集合为真。

使用以下查询:

collection.FindAsync(Builders<YourClass>.Filter.ElemMatch(
                                     f=>f.mylist, item2=>item2.stuff=="a"))

我想,这个也行:

collection.FindAsync(x=>x.mylist.Any(b=>b.stuff=="a"))