Mongodb does not support transactions, so be aware of this when applying it to your project. No matter what the design, do not require mongodb to ensure the integrity of the data.
But mongodb provides many atomic operations, such as saving, modifying, deleting, etc., all of which are atomic operations.
The so-called atomic operation is that either the document is saved to Mongodb, or it is not saved to Mongodb, and the queried document will not be saved completely. Consider the following example, library books and checkout information. An example shows how to ensure that embedded fields associated with atomic operations (update: updates) are synchronized in the same document. You can use it. Embedded in the same document $set Used to specify a key and update the key value, if the key does not exist and create. $unset Used to delete a key. $inc Inc can add or subtract a key whose value is numeric (only a number that meets the requirements) of the document. $push Usage: Append value to field. Field must be an array type. If field does not exist, a new array type will be added. $pushAll Same as $push, except that you can append multiple values to an array field at a time. $pull Removes an equal value from the array field. $addToSet Add a value to the array, and only if the value is not in the array. $pop Delete the first or last element of the array $rename Modify field name $bit Bit operation, integer type 偏移操作符 3.35.1. Atomic operation data model ¶
book = {
_id: 123456789,
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher_id: "oreilly",
available: 3,
checkout: [ { by: "joe", date: ISODate("2012-10-15") } ]
}
db.collection.findAndModify()
Method to determine whether the book can be settled and update the new settlement information.
available
And
checkout
Fields to ensure that these fields are updated synchronously:db.books.findAndModify ( {
query: {
_id: 123456789,
available: { $gt: 0 }
},
update: {
$inc: { available: -1 },
$push: { checkout: { by: "abc", date: new Date() } }
}
} )
3.35.2. Common commands for atomic operation ¶
{ $set : { field : value } }
{ $unset : { field : 1} }
{ $inc : { field : value } }
{ $push : { field : value } }
{ $pushAll : { field : value_array } }
{ $pull : { field : _value } }
{ $pop : { field : 1 } }
{ $rename : { old_field_name : new_field_name } }
{$bit : { field : {and : 5}}}
> t.find() { "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }
> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true )
> t.find() { "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }