MongoDB按特定字段从数组中的对象聚合到对象

时间:2018-07-09 12:58:00

标签: python mongodb aggregation-framework

我想转换这种类型的文档(数组中的对象):

[{"name": "david", "props": {"prop1": {"AR": 9, "NY": 8}, "prop2": 
{"AR": 10, "NY": 9}}},
{"name": "john", "props": {"prop1": {"AR": 7, "NY": 8}, "prop2": {"AR": 
8, "NY": 9}}}]

进入此页面(按“ AR”字段过滤):

{"david": {"prop1": 9, "prop2": 10}, "john": {"prop1": 7, "prop2": 8}}

使用MongoDB聚合。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

有两个非常有用的运算符:$objectToArray将对象转换为k-v对数组,而$arrayToObject将数组转换回对象。因此,您应该使用第一个,重塑对象,然后使用第二个。因此,拥有这样的文档:

{ 
    array: [
        {"name": "david", "props": {"prop1": {"AR": 9, "NY": 8}, "prop2": {"AR": 10, "NY": 9}}},
        {"name": "john", "props": {"prop1": {"AR": 7, "NY": 8}, "prop2": {"AR": 8, "NY": 9}}}
    ] 
}

您可以使用以下汇总:

db.col.aggregate([
    {
        $project: {
            output: {
                $arrayToObject: {
                    $map: {
                        input: "$array",
                        as: "doc",
                        in: {
                            k: "$$doc.name",
                            v: {
                                $arrayToObject: {
                                    $map: {
                                        input: { $objectToArray: "$$doc.props" },
                                        as: "prop",
                                        in: { k: "$$prop.k", v: "$$prop.v.AR" }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
])

哪个输出:

{ "_id" : ..., "output" : { "david" : { "prop1" : 9, "prop2" : 10 }, "john" : { "prop1" : 7, "prop2" : 8 } } }