mongodb - Inline/combine other collection into one collection -
i want combine 2 mongodb collections.
basically have collection containing documents reference 1 document collection. want have inline / nested field instead of separate document.
so provide example:
collection a:
[{ "_id":"90a26c2a-4976-4edd-850d-2ed8bea46f9e", "somevalue": "foo" }, { "_id":"5f0bb248-e628-4b8f-a2f6-fecd79b78354", "somevalue": "bar" }]
collection b:
[{ "_id":"169099a4-5eb9-4d55-8118-53d30b8a2e1a", "collectionaid":"90a26c2a-4976-4edd-850d-2ed8bea46f9e", "some":"foo", "andother":"stuff" }, { "_id":"83b14a8b-86a8-49ff-8394-0a7f9e709c13", "collectionaid":"90a26c2a-4976-4edd-850d-2ed8bea46f9e", "some":"bar", "andother":"random" }]
this should result in collection looking this:
[{ "_id":"90a26c2a-4976-4edd-850d-2ed8bea46f9e", "somevalue": "foo", "collectionb":[{ "some":"foo", "andother":"stuff" },{ "some":"bar", "andother":"random" }] }, { "_id":"5f0bb248-e628-4b8f-a2f6-fecd79b78354", "somevalue": "bar" }]
i'd suggest simple console:
db.collb.find().foreach(function(doc) { var aid = doc.collectionaid; if (typeof aid === 'undefined') { return; } // nothing delete doc["_id"]; // remove property delete doc["collectionaid"]; // remove property db.colla.update({_id: aid}, /* match id b */ { $push : { collectionb : doc }}); });
it loops through each document in collectionb , if there field collectionaid
defined, removes unnecessary properties (_id
, collectionaid
). finally, updates matching document in collectiona using $push
operator add document b field collectionb
. if field doesn't exist, automatically created array newly inserted document. if exist array, appended. (if exists, isn't array, fail). because update
call isn't using upsert
, if _id
in collectionb document doesn't exist, nothing happen.
you can extend delete other fields necessary or possibly add more robust error handling if example document b doesn't match in a.
running code above on data produces this:
{ "_id" : "5f0bb248-e628-4b8f-a2f6-fecd79b78354", "somevalue" : "bar" } { "_id" : "90a26c2a-4976-4edd-850d-2ed8bea46f9e", "collectionb" : [ { "some" : "foo", "andother" : "stuff" }, { "some" : "bar", "andother" : "random" } ], "somevalue" : "foo" }
Comments
Post a Comment