c# - 使用 C# 驱动程序查找 MongoDB 文档并仅匹配数组元素
问题描述
我正在尝试返回一个文档,并且该文档应该对其进行数组过滤,使其仅包含一项。我见过很多类似的问题,但没有一个涉及动态查询。可能有几个限制,所以我必须能够继续添加到过滤器中。
{
"_id" : ObjectId("6058f722e9e41a3d243258dc"),
"fooName" : "foo1",
"fooCode" : 1,
"bar" : [
{
"barCode" : "123",
"barName" : "Rick's Cafe",
"baz" : [
{
"bazId" : "00",
"bazDescription" : "Ilsa"
},
{
"bazId" : "21",
"bazDescription" : "Victor"
}
]
},
{
"barCode" : "456",
"barName" : "Draco Tavern",
"baz" : [
{
"bazId" : "00",
"bazDescription" : "Rick Shumann"
}
]
}
]
}
这是我的尝试,它返回一个包含条形码的数组的文档,并且包含数组的全部内容。
Expression<Func<Foo, bool>> filter = x => x.FooCode == 1;
string barCode = "456"
if (!String.IsNullOrEmpty(barCode))
{
Expression<Func<Foo, bool>> newPred =
x => x.Bar.Any(s => s.BarCode == barCode);
filter = filter.CombineAnd(newPred);
}
var fooQuery =
_fooCollection
.Find(filter);
如何删除不匹配的数组元素,但前提是指定了数组元素?
解决方案
您需要在 MongoDB 中使用聚合。您可以使用unwind拆分数组元素,使用match过滤,使用project选择您想要的键,并使用 id 之类的公共列进行分组。
MongoDB 聚合文档:https ://docs.mongodb.com/manual/aggregation/
推荐阅读
- c++ - 如何阅读复杂的类型?
- java - 没有感觉长度()结果
- applozic - Applozic API - 获取完整图像
- php - DB 中的日期与 Laravel 中的结果不同
- flutter - 如何在颤动中处理文件的空安全性?
- python - 无法访问 Azure IoT Edge API 模块。请求超时
- python - 使用 TriggerDagRunOperator 从没有执行日期触发的子 dag 返回值
- javascript - 如何将所选图像设置为在 Angular 的引导轮播中显示的第一个图像?
- javascript - 简单的事件监听器reactjs不起作用
- java - itext7在pdfa的标题中嵌入字体仅1次