mongodb - 用于查找与特定数组键值匹配的字段的 Mongo 查询
问题描述
我想找出 type="Normal" 和 desc==atr.value 的元素(特定键 atr.key="UDSP" 的 atr.value)。我使用的是 mongo 3.0.4,所以不能使用 $expr。下面是数据集:
JSON
"_id":ObjectId("12345"),
"desc":"Foo Bar",
"type":"Normal",
"atr":[
{
"key":"DSP",
"value":"Goo Bar"
},
{
"key":"UDSP",
"value":"Foo Bar"
}
],
"prod":"yes"
}
{
"_id":ObjectId("12347"),
"desc":"Boo Bar",
"type":"Normal",
"atr":[
{
"key":"DSP",
"value":"Goo Bar"
},
{
"key":"UDSP",
"value":"Foo Bar"
}
],
"prod":"yes"
}
它应该将结果作为 Ist 对象仅作为 type="Normal" 和 atr.value="Foo Bar"(for atr.key="UDSP") 和 desc="Foo Bar"
解决方案
您可以使用此查询。首先根据条件为匹配的文档添加一个字段,然后根据添加的字段进行过滤
db.test.aggregate([
{ $match: { type: "Normal", "atr.key":"UDSP" }},
{ $addFields:{
isDocMatched: {
$anyElementTrue: {
$map:{
input: "$atr",
as: "grade",
in: { $eq: [ "$$grade.value", "$desc" ] }
}
}
}
}},
{ $match: { isDocMatched: true } }
])
推荐阅读
- linux - linux yocto内核驱动开发简单方法
- xamarin.forms - Xamarin 用两种颜色形成圆圈
- javascript - 如何使用 Angular 从用户那里检索地理位置
- android - 广播接收器未激活
- c# - 问答游戏 - 如何在不重复的情况下提出 6 个随机问题?
- angular - 如何获取每个组件或页面留下的所有未完成订阅的计数?
- .net - 在字符串中查找文本
- python - 使用 Tkinter 时如何并行化方法
- gcc - 手动构建的 GCC 和 Clang;Clang 查看系统 C++ 路径,而不是我的 GCC 的
- ocaml - OCaml 的 rectype 推断