Mongo合并到数组中

时间:2017-01-27 12:02:50

标签: mongodb mongodb-query aggregation-framework

我有以下内容:

 {_id: blah, anotherId: "externalId", description: "foo"},
 {_id: blah, anotherId: "externalId", description: "bar"},
 ...

我想:

{_id: blah, anotherId: "externalId", descriptions: ["foo", "bar"]}

我知道我可以简单地写这个,但由于我有数百万条记录,所以它很慢。

db.collectionOfAnotherId.find().forEach(function(r){ 
    var x = {anotherId: r.id, descriptions: []};
    db.myCollection.find({anotherId: x.anotherId}).forEach(function(d){
         x.descriptions.push(d.description); }); 
         db.newCollection.save(x); 
     })

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用聚合框架。例如,请考虑使用 $lookup 运算符对myCollection执行左连接并写入以下 $group 管道的结果使用 $push 创建描述数组的新集合:

db.collectionOfAnotherId.aggregate([
    {
        "$lookup": {
            "from": "myCollection",
            "localField": "id",
            "foreignField": "anotherId",
            "as": "d"
        }
    },
    { "$unwind": "$d" },
    {
        "$group": {
            "_id": "$_id",
            "anotherId": { "$first": "$id" },
            "descriptions": { "$push": "$d.description" }
        }
    },
    { "$out": "newCollection" }
])