如何在数组中使用相同的键检索对象值

时间:2019-06-20 10:08:06

标签: mongodb mongo-shell

我正在尝试从文档数组中获取(过滤)与相同键匹配的所有对象。

文档架构示例:

{
    ...
    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"}
]

感谢

2 个答案:

答案 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"
    ]
}