Atomicity of findAndModify on embedded documents

你离开我真会死。 提交于 2019-12-24 01:44:49

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/21798432/atomicity-of-findandmodify-on-embedded-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!