MongoDB does not support transactions, so be aware of this when applying to your project. No matter what the design, don't ask MongoDB to guarantee the integrity of the data.
But MongoDB provides a number of atomic operations, such as document preservation, modification, deletion, etc., all atomic operations.
The so-called atomic operation is either that the document is saved to MongoDB, or not saved to MongoDB, the query to the document does not appear to save the complete case.
Atomic Manipulation Data Model
Consider the following examples of library books and checkout information.
The example illustrates how to ensure that fields in an embedded field associated with atomic operations (update: Updates) are synchronized in an identical document.
Book= {_id: 123456789,Title: "Mongodb:the Definitive Guide",Author: [ "Kristina Chodorow", "Mike Dirolf." ],Published_date: Isodate("2010-09-24"),Pages: 216,Language: "中文版", Publisher_id: " OReilly ", Available: 3 , Checkout: [{ by: , Date: isodate< Span class= "pun" > ( "2012-10-15" } ] }
You can use the Db.collection.findAndModify () method to determine whether a book can be settled and update new billing information.
Embed the 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< Span class= "pun" >: { by : "abc" , Date: new date () } } }< Span class= "PLN" >} )
Atomic Operations Common Command $set
Used to specify a key and update the key value if the key does not exist and is created.
{:{:}}
$unset
Used to delete a key.
{:{:1}}
$inc
$inc can increase or decrease the number of keys in a document that are numeric (only for numbers that meet the requirements).
{:{:}}
$push
Usage:
{:{:}}
Append value To field, field must be array type, if field does not exist, a new array type will be added.
$pushAll
With $push, it is possible to append multiple values to an array field at a time.
{:{:}}
$pull
Deletes an equal value from the array field.
{:{:}}
$addToSet
Adds a value to the array, and only if the value is not inside the array.
$pop
Delete the first or last element of an array
{:{:1}}
$rename
Modify field names
{:{:}}
$bit
Bit operation, integer type
{: {: {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 }, Span class= "pun" >{ "by" : "Jane" , "votes" : 7 } ] }
MongoDB Atomic Operation