MongoDB聚合-在一个数组中显示来自不同数组的值

时间:2019-05-14 10:53:08

标签: mongodb aggregation-framework

我有这种类型的数据

{ 
"_id" : 6444, 
"name" : [
    {
        "name" : "John", 
        "sourcesID" : [
            1, 
            2
        ]
    }, 
    {
        "name" : "Jack", 
        "sourcesID" : [
            3, 
            4 
        ]
    }       
    ],
"address" : [
    {
        "city" : "Chicago", 
        "sourcesID" : [
            3, 
            4 
        ]
    }, 
    {
        "city" : "Boston", 
        "sourcesID" : [
            5, 
            6
        ]
    }       
]       

}

我想聚合数据,以便能够匹配特定的sourcesID,并找到来自该源的所有信息类型。

这就是我要实现的目标

{"type" : "name", "sourceID" : 1}
{"type" : "name", "sourceID" : 2}
{"type" : "name", "sourceID" : 3}
{"type" : "name", "sourceID" : 4}
{"type" : "address", "sourceID" : 3}
{"type" : "address", "sourceID" : 4}
{"type" : "address", "sourceID" : 5}
{"type" : "address", "sourceID" : 6}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

假设总是有sourceID字段,您可以运行$objectToArray进行转换以能够动态读取对象键,然后运行$unwind三次以获取每个sourceID单个文档:

db.collection.aggregate([
    {
        $project: {
            data: {
                $filter: {
                    input: { $objectToArray: "$$ROOT" },
                    cond: {
                        $ne: [ "$$this.k", "_id" ]
                    }
                }
            }
        }
    },
    { $unwind: "$data" },
    { $unwind: "$data.v" },
    { $unwind: "$data.v.sourcesID" },
    {
        $project: {
            _id: 0,
            type: "$data.k",
            sourceID: "$data.v.sourcesID"
        }
    }
])

Mongo Playground