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

How to retrieve object values with same key inside an array

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

文档架构示例:

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

谢谢

编辑

确实可以按照您期望的格式进行这样的查询和输出。您可以先执行 $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"
    ]
}

unwinding数组再操作

就可以得到这个数组
    db.demo.aggregate([
        {
            $unwind:"$aut_comms"
        },
        {
            $match:{"aut_comms.name":"Aragon"}
        },
        {
            $group:{
                _id:null,
                result: {$push:"$aut_comms.province"}
            }
        }
   ])