问题
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