2

On mongodb manual there is an example for atomic operations on a single document.

book = {
          _id: 123456789,
          title: "MongoDB: The Definitive Guide",
          available: 3,
          checkout: [ { by: "joe", date: ISODate("2012-10-15") } ]
        }

The manual states that the below operation is atomic:

db.books.findAndModify ( {
   query: {
            _id: 123456789,

            available: { $gt: 0 }
          },
   update: {
             $inc: { available: -1 },
             $push: { checkout: { by: "abc", date: new Date() } }
           }
} )

My question is what would happen if available field was an embedded document. Such as below:

book = {
          _id: 123456789,
          title: "MongoDB: The Definitive Guide",
          available: [ { value: 3, valueFloat: 3.00 ] },
          checkout: [ { by: "joe", date: ISODate("2012-10-15") } ]
        }

Could I still do this operation atomically? If so, how?

Emre Kenci
  • 2,715
  • 4
  • 26
  • 35

1 Answers1

4

Since subdocuments are basically just fields within the main document any updates to them are also atomic.

MongoDB has transactions per document and that applies to the entire document, including its subdocuments.

It should be noted that not just findAndModify is atomic. Any operation on a single document, whether it be update() or remove() is atomic.

Sammaye
  • 43,242
  • 7
  • 104
  • 146
  • Thanks a bunch. The difference between calling find(_id) and then update(_id, newvalue) and calling findandmodify(_id, newvalue) is that the document can be updated between find() and update() calls. But with findAndModify no other read/write operations can be made on the document until the execution of findAndModify is complete. Am I correct? I guess that is why this example is chosen? Thanks again, that really helped. – Emre Kenci Feb 15 '14 at 14:03
  • @AntonAnsgar indeed there can be interferrance but if you call update with a find condition then it is atomic, same as findandmodify – Sammaye Feb 15 '14 at 14:56