MongoDB update with condition

前端 未结 6 676
鱼传尺愫
鱼传尺愫 2020-11-29 10:11

I\'m trying to update some field in my collection depending on a condition.

I want to set field active to true if the condition is tr

6条回答
  •  情歌与酒
    2020-11-29 10:49

    Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:

    // { a: "Hello", b: "World" }
    // { a: "Olleh", b: "Dlrow" }
    db.collection.update(
      {},
      [ { $set: { active: { $eq: [ "$a", "Hello" ] } } } ],
      { multi: true }
    )
    // { a: "Hello", b: "World", active: true  }
    // { a: "Olleh", b: "Dlrow", active: false }
    
    • The first part {} is the match query, filtering which documents to update (in our case all documents).

    • The second part [ { $set: { active: { $eq: [ "$a", "Hello" ] } } } ] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias of $addFields. Then any aggregation operator can be used within the $set stage; in our case a conditional equality check on which depends the value to use for the new active field.

    • Don't forget { multi: true }, otherwise only the first matching document will be updated.

提交回复
热议问题