DShultz
DShultz

Reputation: 4541

Mongo query to update field and modify the data currently in the column(s)

I'm trying to write a Mongo update query that updates a specific column and revises it using the current data in that field. So instead of:

$set: {
  displayName: 'test'
}

I need to append something to the existing data like:

$set: {
  displayName: 'test' + displayName
}

But the above syntax doesn't work - I'm just looking for the syntax to simply update a column to it's current value + 'test'.

Upvotes: 2

Views: 1190

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

There is no way for referencing document fields in update operation. You should move execution to the client and iterate cursor with forEach:

db.collection.find({ /* your query here */}).forEach(function(doc) {
     db.collection.update({_id: doc._id}, {$set: {displayName: 'test' + doc.displayName}});
})

Upvotes: 2

Related Questions