Mika
Mika

Reputation: 5845

Mongo merge into array

I have the following:

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

I want:

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

I know I can simply write this but it's very slow as I have millions of records.

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); 
     })

Any ideas?

Upvotes: 1

Views: 74

Answers (1)

chridam
chridam

Reputation: 103445

You could use the aggregation framework for this. For example, consider using the $lookup operator to do a left join to myCollection and writing the results of the following $group pipeline to the new collection using $push to create the descriptions array as:

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" }
])

Upvotes: 1

Related Questions