Thiago Cruz
Thiago Cruz

Reputation: 65

Count recurrences in a collection and merge aggregation result to another collection

I need to count the recurrences of a value in the collection A, so I do

db.collectionA.aggregate( [ { $group : { name : "$name", count :{$sum: 1 } } } ] )

And have something like

{
  "name": "Bruce",
  "count": 2
},
{
  "_id": "Alfred",
  "count": 3
}

Then I need to get this result and populate a field of the collection B, I imagine something like a forEach but don't know how to implement

db.collectionB.findAndModify({query: {"name":forEach of the pervious result},
update:{"nameRecurrences": value of the count}})

Upvotes: 1

Views: 38

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17925

Looking at your aggregation pipeline :

db.collectionA.aggregate( [ 
      { $group : { _id : '$name', name : {$first : "$name"}, nameRecurrences :{$sum: 1 } } }, // renamed field `nameRecurrences` to match with field name in `collection-B`
      {$project : {_id : 0}} ] ) // Removing _id to avoid conflicts on merge

On MongoDB version >= 4.2 you can use $merge aggregation operator to merge result of aggregation pipeline on one collection to another collection :

Just add below stage as last stage of aggregation pipeline :

{$merge : { into: { db: "dbName", coll: "collectionB" }, on: "name", whenNotMatched: "discard"}} // Remember to create unique index on `name` field on `collectionB`

Since you're using MongoDB version 3.6.16 :

If the collection has to be created now then you can use $out, but if it's an existing collection with lot of fields in each document apart from just name & nameRecurrences then you can try this in code :

Since you've different filters and their respective update part, then you can take advantage of .bulkWrite() to update multiple documents :

let bulkArr = []

for (const i of aggregationResult){
    bulkArr.push( { updateOne : {
        "filter" : { "name" : i.name },
        "update" : { $set : { "nameRecurrences" : i.nameRecurrences } }
     } })
}

db.collectionB.bulkWrite(bulkArr)

Upvotes: 1

Related Questions