How do I append Mongo DB aggregation results to an existing collection?

前端 未结 3 488
刺人心
刺人心 2021-01-11 09:45

I am trying to perform several insertions on an existent Mongo DB collection using the following code

db.dados_meteo.aggregate( [
                  { $match          


        
3条回答
  •  孤独总比滥情好
    2021-01-11 10:35

    The short answer is "you can't":

    If the collection specified by the $out operation already exists, then upon completion of the 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 pre-existing collection.

    As a workaround, you can copy the collection document specified by $out to a "permanent" collection just after aggregation, in one of a several ways (non of which is ideal though):

    • copyTo() is the easiest, mind the Warning. Don't use other for small results.
    • Use JS: db.out.find().forEach(function(doc) {db.target.insert(doc)})
    • Use mongoexport / mongoimport

提交回复
热议问题