tengo lo siguiente:
{_id: blah, anotherId: "externalId", description: "foo"}, {_id: blah, anotherId: "externalId", description: "bar"}, ...Deseo:
{_id: blah, anotherId: "externalId", descriptions: ["foo", "bar"]}Sé que simplemente puedo escribir esto, pero es muy lento ya que tengo millones de registros.
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); })¿Algunas ideas?
Podría usar el marco de agregación para esto. Por ejemplo, considere usar el operador de $lookup para hacer una unión izquierda a myCollection y escribir los resultados de la siguiente canalización de $group en la nueva colección usando $push para crear la matriz de descripciones como:
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" } ])