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
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
.