MongoDB updateMany with Conditional

前端 未结 1 951
死守一世寂寞
死守一世寂寞 2021-01-15 13:09

I have a large DB with various inconsistencies. One of the items I would like to clear up is changing the country status based on the population.

A Sample of the dat

相关标签:
1条回答
  • 2021-01-15 13:29

    You really want want bulkWrite() using two "updateMany" statements within it instead. Aggregation expressions cannot be used to do "alternate selection" in any form of update statement.

    db.country.bulkWrite([
      { "updateMany": {
        "filter": { "pop": { "$lt": 20000000 } },
        "update": { "$set": { "country": "Small Country" } }
      }},
      { "updateMany": {
        "filter": { "pop": { "$gt": 20000000 } },
        "update": { "$set": { "country": "Large Country" } } 
      }}
    ])
    

    There is still an outstanding "feature request" on SERVER-6566 for "conditional syntax", but this is not yet resolved. The "bulk" API was actually introduced after this request was raised, and really can be adapted as shown to do more or less the same thing.

    Also using $out in an aggregation statement as was otherwise suggested is not an option to "update" and can only write to a "new collection" at present. The slated change from MongoDB 4.2 onwards would allow $out to actually "update" an existing collection, however this would only be where the collection to be updated is different from any other collection used within the gathering of data from the aggregation pipeline. So it is not possible to use an aggregation pipeline to update the same collection as what you are reading from.

    In short, use bulkWrite().

    0 讨论(0)
提交回复
热议问题