The best MongoDB atomic operations Tutorial In 2024, In this tutorial you can learn Atomic data model,Atomic operations commonly used commands,
mongodb does not support transactions, therefore, in the application of your project, pay attention to this point. Whatever the design, we do not ask mongodb ensure data integrity.
But mongodb provides many atomic operations, such as saving a document, modify, delete, etc., are atomic operations.
Either this is the so-called atomic operation to save the document to Mongodb, or not saved to Mongodb, the document does not have to query intact will not happen.
Consider the following example, library books and transaction information.
In one example illustrates how to ensure that the same document embedded fields related atomic operations (update: update) fields are synchronized.
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 db.collection.findAndModify () method to determine whether books can be updated with new settlement and billing information.
Embedded in the same document available and checkout fields to ensure that these fields are synchronized update:
db.books.findAndModify ( { query: { _id: 123456789, available: { $gt: 0 } }, update: { $inc: { available: -1 }, $push: { checkout: { by: "abc", date: new Date() } } } } )
It is used to specify a key and update the key, if the key does not exist and create.
{ $set : { field : value } }
To remove a key.
{ $unset : { field : 1} }
$ Inc can be a numeric value of the document (only to meet the requirements of digital) keys to increase or decrease operations.
{ $inc : { field : value } }
usage:
{ $push : { field : value } }
The value added to the field to go inside, it must be an array type field job, if the field does not exist, a new array type added.
With $ push, but once you can append multiple values into an array field.
{ $pushAll : { field : value_array } }
To delete a field from an array of value equal value.
{ $pull : { field : _value } }
Adding a value into the array, and only when the value is not within the array to increase.
The first or the last element of the array of deleted
{ $pop : { field : 1 } }
Modify the field name
{ $rename : { old_field_name : new_field_name } }
Bit operations, integer type
{$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 } ] }