Multiply field by value in Mongodb

后端 未结 4 896
旧时难觅i
旧时难觅i 2020-12-01 03:15

I\'ve been looking for a way to create an update statement that will take an existing numeric field and modify it using an expression. For example, if I have a field called

4条回答
  •  没有蜡笔的小新
    2020-12-01 03:42

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

    // { price: 19.99 }
    // { price: 2.04  }
    db.collection.update(
      {},
      [{ $set: { price: { $multiply: [ 0.5, "$price" ] } } }],
      { multi: true }
    )
    // { price: 9.995 }
    // { price: 1.02  }
    
    • The first part {} is the match query, filtering which documents to update (all documents in this case).

    • The second part [{ $set: { price: ... } }] 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. Note how price is modified directly based on the its own value ($price).

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

提交回复
热议问题