3

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?

Paula Code
  • 61
  • 2
  • 5

1 Answers1

2
  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

playground

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); 
               }
             );
R2D2
  • 9,410
  • 2
  • 12
  • 28