Amith George
Amith George

Reputation: 5916

Update one property's value to the value of another property in the same document

How can we replicate the following sql query in MongoDb?

update Person set Alias = Name;

where the Person table has the columns Alias, Name

I want the query to affect multiple rows. It doesn't matter if the update query cannot support upserts, I only need to update & not insert.

Upvotes: 0

Views: 160

Answers (2)

William Z
William Z

Reputation: 11129

Unfortunately, that functionality is not available in MongoDB. You will need to loop through the documents, updating them one-at-a-time, and doing a read-update pair.

If you want this to be concurrency-safe, you'll need to implement some sort of locking; either optimistic or pessimistic.

Upvotes: 2

Todd Murray
Todd Murray

Reputation: 423

myDb.myCollection.find({}).forEach(
function (person) { 
      person.Alias = person.Name
      myDb.myCollection.save(person)
}
)

Upvotes: 0

Related Questions