MongoDB atomic operations
mongodb does not support transactions, so please pay attention to this when applying it in your project. No matter what the design, do not require mongodb to ensure data integrity.
But mongodb provides many atomic operations, such as document saving, modification, deletion, etc., which are all atomic operations.
The so-called atomic operation means that either the document is saved to Mongodb, or it is not saved to Mongodb. There will be no situation where the queried document is not saved completely.
Atomic Operation Data Model
Consider the following example of library books and checkout information.
The example illustrates how to ensure that fields associated with embedded fields in atomic operations (update: update) are synchronized in the same document.
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") } ] }
You can use the db.collection.findAndModify() method to determine whether a book can be settled and update the new settlement information.
Embed available and checkout fields in the same document 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() } } } } )
Common commands for atomic operations
$set
Used to specify a key and update the key value. If the key does not exist, create it.
{ $set : { field : value } }
$unset
is used to delete a key.
{ $unset : { field : 1} }
$inc
$inc can increase or decrease a key in the document whose value is numeric (can only be a number that meets the requirements).
{ $inc : { field : value } }
$push
Usage:
{ $push : { field : value } }
Append the value to the field. The field must be an array type. If the field does not exist, a new array will be added. Type added.
$pushAll
Same as $push, except that multiple values can be appended to an array field at one time.
{ $pushAll : { field : value_array } }
$pull
Delete a value equal to value from the array field.
{ $pull : { field : _value } }
$addToSet
Add a value to the array, and only add it if the value is not in the array.
$pop
Delete the first or last element of the array
{ $pop : { field : 1 } }
$rename
Modify the field name
{ $rename : { old_field_name : new_field_name } }
$ bit
Bit operation, integer type
{$bit : { field : {and : 5}}}
Offset operator
> 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 } ] }