mongodb update field a to be value of field b

Viewed 8158

I am trying to run a mongo query to update the value of one field with the value of another field. I have the following documents:

{ "_id" : ObjectId("56e0a3a2d59feaa43fba49d5"), "old" : 16, "new" : 17 }

{ "_id" : ObjectId("56e0a3a2d59feaa43fba49d3"), "old" : 11, "new" : 12 }

I would like to make it look like this after update:

{ "_id" : ObjectId("56e0a3a2d59feaa43fba49d5"), "old" : 16, "new" : 16 }

{ "_id" : ObjectId("56e0a3a2d59feaa43fba49d3"), "old" : 11, "new" : 11 }

I've tried the following with no luck

db.runCommand(
{
 findAndModify: "testData",
 query: { $where: "this.new != this.old" },
 update: { old : this.new },
 upsert: true
}
)

and

db.testData.update( { $where: "this.new != this.old" }, { $set: { old: this.new } } );

Is this even possible with mongoDb?

I would like to do it in a single query and not iterate through each document.

Any ideas would be greatly appreciated.

Thank you

2 Answers
Related