Update if Current
"Update if Current" is a manual way to insure atomicity during an update, and for this we:
Fetch the object we want to update.
Modify the object locally.
Update where the condition should match the old value (from step 1)
Let’s assume we have a collection ‘foo’ like so:
> db.foo.find().pretty()
{
"_id" : ObjectId("4f9808648859c65d"),
"array" : [
{"text" : "foo", "value" : 11},
{"text" : "bar", "value" : 22},
{"text" : "foobar", "value" : 33}
]
}
And let's say we want to update the array to change the text to "blah" for every field that has a value greater than 20. As we saw in the previous post, Mongo supports updates within the array only for the first relevant match (where text = "bar" in this case) but we would like to modify the one that has 33 as value since it's a match.
We, first, fetch the object we want: var obj = db.foo.findOne({"_id" : ObjectId("4f9808648859c65d")}) var old_array = obj.get("array")
Then we update the array locally to: var new_array = [
{"text" : "foo", "value" : 11},
{"text" : "blah", "value" : 22},
{"text" : "blah", "value" : 33}
]
We update the collection foo where the array matches the old_array: db.foo.update( {"_id" : ObjectId("4f9808648859c65d"), "array" : old_array} ,{$set : {"array" : new_array}})
This is a 'dirty' solution that will insure the atomic update for this case. A better way to do this would be to keep a version variable in the object, and increment it on each update.











