If you add a version element to your document you can use it to track
changes to the document. I'll use an integer version number in the
example below, but an ObjectId is another possibility.
I'm working with this slightly different document (I've only changed
_ids to integers to make typing easier):
> db.test.find()
{ "_id" : 123, "version" : 1, "widgets" : [
{
"_id" : 0,
"views" : 3,
"comments" : 7
},
{
"_id" : 1,
"views" : 0,
"comments" : 1
},
{
"_id" : 2,
"views" : 2,
"comments" : 8
}
], "dtcreate" : ISODate("2011-07-15T14:08:47.257Z") }
>
Here's some sample shell code to simulate "extracting" the widget from
the document and updating it client side:
> var document = db.test.findOne()
> var widget = document.widgets[0]
> widget.views = 5
5
> widget.comments = 9
9
> widget
{ "_id" : 0, "views" : 5, "comments" : 9 }
>
Now we can use the findAndModify command to update the document while
making sure no one else has updated the document in the database in
the meantime:
> db.test.runCommand({
... findAndModify : "test",
... query : { _id : 123, version : document.version, "widgets._id" :
0 },
... update : { $inc : { version : 1 }, $set : { widget : widget } },
... new : true
... })
{
"value" : {
"_id" : 123,
"dtcreate" : ISODate("2011-07-15T14:08:47.257Z"),
"version" : 2,
"widget" : {
"_id" : 0,
"views" : 5,
"comments" : 9
},
"widgets" : [
{
"_id" : 0,
"views" : 3,
"comments" : 7
},
{
"_id" : 1,
"views" : 0,
"comments" : 1
},
{
"_id" : 2,
"views" : 2,
"comments" : 8
}
]
},
"ok" : 1
}
>
If we try and run the findAndModify command when the version numbers
don't match anymore we get:
> db.test.runCommand({
... findAndModify : "test",
... query : { _id : 123, version : document.version, "widgets._id" :
0 },
... update : { $inc : { version : 1 }, $set : { widget : widget } },
... new : true
... })
{ "errmsg" : "No matching object found", "ok" : 0 }
On Jul 14, 9:58 pm, "Nat" <
nat.lu...@gmail.com> wrote:
> You would need to keep a version data or something that can identify version in there and use that as part of criteria.
http://www.mongodb.org/display/DOCS/Updating
>
> Another option if u want to simply increment comments count of certain object. You can use update modifier $inc with $ positional operator.
http://www.mongodb.org/display/DOCS/Updating