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

前端 未结 3 491
刺人心
刺人心 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:42

    Starting Mongo 4.2, the new $merge aggregation operator (similar to $out) allows merging the result of an aggregation pipeline into the specified collection:

    Given this input:

    db.source.insert([
      { "_id": "id_1", "a": 34 },
      { "_id": "id_3", "a": 38 },
      { "_id": "id_4", "a": 54 }
    ])
    db.target.insert([
      { "_id": "id_1", "a": 12 },
      { "_id": "id_2", "a": 54 }
    ])
    

    the $merge aggregation stage can be used as such:

    db.source.aggregate([
      // { $whatever aggregation stage, for this example, we just keep records as is }
      { $merge: { into: "target" } }
    ])
    

    to produce:

    // > db.target.find()
    { "_id" : "id_1", "a" : 34 }
    { "_id" : "id_2", "a" : 54 }
    { "_id" : "id_3", "a" : 38 }
    { "_id" : "id_4", "a" : 54 }
    

    Note that the $merge operator comes with many options to specify how to merge inserted records conflicting with existing records.

    In this case (with the default options), this:

    • keeps the target collection's existing documents (this is the case of { "_id": "id_2", "a": 54 })

    • inserts documents from the output of the aggregation pipeline into the target collection when they are not already present (based on the _id - this is the case of { "_id" : "id_3", "a" : 38 })

    • replaces the target collection's records when the aggregation pipeline produces documents existing in the target collection (based on the _id - this is the case of { "_id": "id_1", "a": 12 } replaced by { "_id" : "id_1", "a" : 34 })

提交回复
热议问题