In-depth analysis of mongoDB atomic operations

Source: Internet
Author: User
Tags cas comments commit mongodb redis

Redis adopts an asynchronous I/O non-blocking single-process model. Each Redis command is atomic. What about mongoDB? What atomic operations does mongo have? What are the techniques for implementing transactional operations?

1. Make Atomic modifications to a single document

MongoDB ensures atomic modification of multiple fileds of a single document. You can use findAndModify to perform atomic CAS operations (check and set) on a single document.

For example, the following is an atomic CAS operation. First, select the document with the _ id of 123 (note that only one document is selected), and then add 1 to the counter count, change the status field to true and return the modified result.

Db. colleciton. findAndModify ({query: {_ id: '000000'}, $ inc: {count: 1}, $ update: {status: true}, new: true );

2. Use the $ isolate operator for multiple documents

The $ isolate operator can isolate modifications to multiple documents. For concurrent write operations on other threads, $ isolate ensures that the corresponding documents cannot be modified by other threads before submission. For read operations on other threads, $ isolate ensures that other threads cannot read uncommitted data.

However, $ isolate has a verification performance problem, because in this case, the thread holds the lock for a long time, seriously affecting the concurrency of mongo. In addition, $ isolate cannot guarantee the consistency of modifications to multiple documents (all-or-nothing). $ isolate may fail to modify only some documents.

3. Implement transactional operations at the semantic level

MongoDB officially provides a two-phase commit (two-phase commit). The basic principle is to use the idempotence of write operations. For more information about the implementation, see the official website. However, idempotence is an important precondition for implementing transactions: the business does not care about the inconsistency of the intermediate state. Idempotence can guarantee final consistency, but inconsistency may occur in the middle.


Atomic operation data model

Consider the following example: library books and checkout information.

The example shows how to ensure that fields associated with 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 books can be settled and update new settlement information.

The available and checkout fields embedded in the same document ensure that these fields are synchronously updated:

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

It is used to specify a key and update the key value. If the key does not exist, it is created.

{$ Set: {field: value }}
$ Unset

Used to delete a key.

{$ Unset: {field: 1 }}
$ Inc

$ Inc can increase or decrease the key of a document with a value of the numeric type (only a number meeting the requirements.

{$ Inc: {field: value }}
$ Push


{$ Push: {field: value }}

Append the value to the field. The field must be of the array type. If the field does not exist, an array type is added.

$ PushAll

The same as $ push, but multiple values can be appended to an array field at a time.

{$ PushAll: {field: value_array }}
$ Pull

Deletes a value equal to the value from the array field.

{$ Pull: {field: _ value }}
$ AddToSet

Add a value to the array. This value is added only when it is not in the array.

$ Pop

Deletes the first or last element of an array.

{$ Pop: {field: 1 }}
$ Rename

Modify 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': 'job'}, {$ inc: {'comments. $. votes ': 1 }}, false, true)
> T. find () {"_ id": ObjectId ("4b97e62bf1d8c7152c9ccb74"), "title": "ABC", "comments": [{"by": "joe ", "votes": 4 },{ "by": "jane", "votes": 7}]}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.