Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to aggregate and merge the result into a collection?

Tags:

mongodb

I want to aggregate and insert the results into an existing collection, without deleting that collection. The documentation seems to suggest that this isn't directly possible. I find that hard to believe.

The map-reduce functionality has 'output modes', including 'merge', which does what I want. I'm looking for the equivalent for aggregation.

The new $out aggregation stage supports inserting into a collection, but it replaces the collection rather than updating it. If I did this I would (I think) have to run another map-reduce to merge this into another collection, which seems inefficient.

Am I missing something or is the functionality just missing from the aggregation feature?

like image 995
Joe Avatar asked Jan 07 '14 16:01

Joe


2 Answers

I used the output from aggregation to insert/merge to collection:

    db.coll2.insert(
      db.coll1.aggregate([]).toArray()
    )
like image 198
NBjerre Avatar answered Oct 18 '22 19:10

NBjerre


Reading the documentation answers this question quite precisely. Atm mongo is not able to do what you want.

The $out operation creates a new collection in the current database if one does not already exist. The collection is not visible until the aggregation completes. If the aggregation fails, MongoDB does not create the collection.

If the collection specified by the $out operation already exists, then upon completion of aggregation the $out stage atomically replaces the existing collection with the new results collection. The $out operation does not change any indexes that existed on the previous collection. If the aggregation fails, the $out operation makes no changes to the previous collection.

like image 24
chk Avatar answered Oct 18 '22 21:10

chk