MongoDB update. Trying to set one field from a property of another

前端 未结 4 1674
误落风尘
误落风尘 2021-02-05 20:08

What I\'m trying to do is pretty straightforward, but I can\'t find out how to give one field the value of another.

I simply want to update one field with the character

4条回答
  •  生来不讨喜
    2021-02-05 20:53

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

    // { "_id" : ObjectId("5e84c..."), "field1" : 12, "field2" : "world" }
    db.collection.update(
      { "_id" : ObjectId("5e84c...") },
      [{ $set: { field1: { $strLenCP: "$field2" } } }]
    )
    // { "_id" : ObjectId("5e84c..."), "field1" : 5, "field2" : "world" }
    
    • The first part {} is the match query, filtering which documents to update.

    • The second part [{ $set: { field1: { $strLenCP: "$field2" } } }] 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 for $addFields. Any aggregation operator can be used within the $set stage; in our case $strLenCP which provides the length of field2.

提交回复
热议问题