I have a collection of people:
{
name: Juan,
age: 21
}
and now , I want to achieve the following:
{
name: Juan,
age: 21,
name_reply:Juan
}
I have tried using:
db.people.updateMany(
{"name_reply":null},
[{$set:{name_reply:"$name"}}]
);
but the following appears. Expected type object but found array.
How could I update a mongo field using the value of another field?
db.collection.update({
"name_reply": null
},
[
{
"$set": {
"name_reply": "$name"
}
}
],
{
multi: true
})
But indeed this is only for mongodb version >=4.2 where you can provide aggregation pipeline to the update query
for earlier versions you can check this answer here
something like this could do the job most probably:
db.collection.find({"name_reply":null}).snapshot().forEach(
function (doc) {
doc.name_reply = doc.name;
db.collection.save(doc);
}
);