查询嵌套组并推入mongodb

时间:2017-04-09 09:53:37

标签: mongodb

我第一次尝试使用mongoDB。我需要将我的数据从一个集合聚合到另一个集合。尝试此代码但由于意外错误而无法执行:

  

“意外表达$ group”

db.import.aggregate([{
        $group: {
            _id: {
                day: "$Day",
                month: "$Month",
                year: "$Year"
            },
            manufacturers: {
                $push: {
                    $group: {
                        _id: {
                            manID: "$Man_ID",
                            man_name: "$Man_Name"
                        },
                        types: {
                            $push: {
                                model_name: "$Model_name",
                                body_type: "$Body_type"
                            }
                        }
                    }
                }
            }
        }
    },
    { $out: "output_doc" }
], {
    allowDiskUse: true,
    cursor: {}
});

预期产出:

["$Day","$Month","$Year",
    ["$Man_ID","$Man_Name", 
       ["$Model_name","$Body_type"]
    ]
]

1 个答案:

答案 0 :(得分:1)

您可以在没有任何操作符的情况下推送新的_id字段并创建types数组:

db.import.aggregate([{
    $group: {
        _id: {
            day: "$Day",
            month: "$Month",
            year: "$Year"
        },
        manufacturers: {
            $push: {
                _id: {
                    manID: "$Man_ID",
                    man_name: "$Man_Name"
                },
                types: [{ model_name: "$Model_name", body_type: "$Body_type" }]
            }
        }
    }
}])