0

I am trying to do the following in mongodb

update table1 set name = name1

I am using:

db.table1.updateMany(
{},
{
    $set: {name: "$name1".}
}
)

However when i check the collection, the value for name = $name1 (meaning it just put it in as a string). I am expecting the value of name1 to be in the field name.

Have tried this on 4.2.

Faisal M
  • 173
  • 2
  • 6
  • 1
    Does this answer your question? [Update MongoDB field using value of another field](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) – CherryDT Mar 09 '20 at 13:45
  • 1
    Use an aggregation pipeline (Mongo 4.2+). See https://stackoverflow.com/a/56551339/1871033 - `db.table.update({}, [{$set: {name: '$name1'}}], {multi: true})` – CherryDT Mar 09 '20 at 13:47
  • Doesnt work. Your syntax says: "BSON field 'update.updates.u' is the wrong type 'array', expected type 'object'". And if i remove the [] for the array, it just writes the string value into the field as in my original question. – Faisal M Mar 09 '20 at 13:54
  • @CherryDT - no the other article is where i got the above syntax. it doesnt work. Server is running mongo 4.0, and my shell is 4.2. If that makes any difference at all. – Faisal M Mar 09 '20 at 13:56
  • OK so please update your question, you said you tried it on Mongo 4.2 but it's actually 4.0 which doesn't have this feature indeed. So you'll have to use one of the other answers from the other thread. – CherryDT Mar 09 '20 at 13:58

1 Answers1

0

You will need to run aggregation pipeline for this:

Imagine you inserted your document like this:

db.table1.insertOne({ _id: 1, name1: "1"})

Then you want to update the existing document:

db.table1.updateOne( {_id: 1},
  [
    { $replaceRoot: { newRoot:
       { $mergeObjects: [ "$$ROOT" , { name: "$name1" } ] }
    } }
  ]
)

Or a simpler syntax would be:

db.table1.updateOne({_id: 1}, [{ $set: { name: '$name1' } }])
Yahya
  • 3,386
  • 3
  • 22
  • 40