j3d
j3d

Reputation: 9724

MongoDB: How to increment a value when replacing an entire document

Let's assume the following document:

{
  "_id" : ObjectId("53b986e2fe000000019a5a13"),
  "name" : "Joe",
  "birthDate" : "2080-12-11",
  "publications" : [
    { "title" : "title 1", "description" : "description 1" },
    { "title" : "title 2", "description" : "description 2" }
  ],
  "version" : 1
}

I need to replace the whole document like this...

db.test.update({"_id": ObjectId("53b986e2fe000000019a5a13")}, {
  "_id" : ObjectId("53b986e2fe000000019a5a13"),
  "name" : "Joe",
  "birthDate" : "1980-12-11",
  "publications" : [
    { "title" : "bye bye", "description" : "Blah blah" },
    { "title" : "title 2", "description" : "description 2" },
    { "title" : "title 3", "description" : "description 3" }
  ]
})

... but I also need to increment the document version by one. Since in that case $inc is not allowed, is there any alternative?

Upvotes: 0

Views: 450

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

I don't know of any way to combine wholesale replacement in the same subdocument as an increment, but if you can put your data in a sub document so you can use $set, it'll work;

> db.test.insert({ doc: { a: 1 }, version: 1 })

> db.test.update({ }, { $set: { doc: { b: 1 } }, $inc: { version: 1 } })

> db.test.find().pretty()
{
    "_id" : ObjectId("53c1600fd904c83d877daf21"),
    "doc" : {
        "b" : 1
    },
    "version" : 2
}

Note the wholesale replacement of doc and the increment of version. If you choose to set individual fields at the top level (ie not changing your document structure), you'll be required to also unset existing values you want to remove, if that's not a problem that's of course also an option.

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311835

You can combine $inc that updates version with a $set that updates the rest of the fields:

db.test.update({"_id": ObjectId("53b986e2fe000000019a5a13")}, {
    $set: {
        "name" : "Joe",
        "birthDate" : "1980-12-11",
        "publications" : [
            { "title" : "bye bye", "description" : "Blah blah" },
            { "title" : "title 2", "description" : "description 2" },
            { "title" : "title 3", "description" : "description 3" }
        ]
    },
    $inc: {version: 1}
})

Upvotes: 1

Related Questions