我正在尝试从文档数组中获取(过滤)与相同键匹配的所有对象。
文档架构示例:
{
...
country: "ES",
aut_comms:
[
...
{name: "Aragon", province: "Huesca"},
{name: "Aragon", province: "Teruel"},
{name: "Aragon", province: "Zaragoza"},
{name: "Madrid", province: "Madrid"}
...
]
}
如果可能,将仅从查询中检索与相同键匹配的对象中的值。结果是组成如下的数组:["Huesca", "Teruel", "Zaragoza"]
与过滤器匹配的对象数组也可以解决问题:
[
{name: "Aragon", province: "Huesca"},
{name: "Aragon", province: "Teruel"},
{name: "Aragon", province: "Zaragoza"}
]
感谢
答案 0 :(得分:1)
首先,您可以unwinding数组然后对其进行操作
db.demo.aggregate([
{
$unwind:"$aut_comms"
},
{
$match:{"aut_comms.name":"Aragon"}
},
{
$group:{
_id:null,
result: {$push:"$aut_comms.province"}
}
}
])
答案 1 :(得分:0)
修改
确实有可能以您期望的格式进行这种查询和输出。您可以先执行$unwind
或$match
。就我个人而言,我更喜欢先进行$match
,因为这样会限制$unwind
操作生成的(不必要的)文档的数量。
db.getCollection('col').aggregate([
{$match: {"aut_comms.name": "Aragon"}},
{$project: {_id: 0, "aut_comms": 1}},
{$unwind: "$aut_comms"},
{$match: {"aut_comms.name": "Aragon"}},
{$project: {"province": "$aut_comms.province"}},
{$group: {
_id: null,
province: {$push: "$province"}
}}
])
输出将是:
/* 1 */
{
"_id" : null,
"province" : [
"Huesca",
"Teruel",
"Zaragoza"
]
}