What is Atomicity in MongoDB and How to Achieve it?
Last Updated :
16 May, 2024
Atomicity ensures that all changes within a single operation are either fully completed or not applied at all, preventing data corruption and inconsistencies.
Atomicity and How to Achieve it
Atomicity in database operations ensures that all changes within a single operation are either fully applied or not applied at all, thus maintaining data integrity. In MongoDB, atomicity is achieved through mechanisms like transactions and single-document operations.
Operation Example: insertOne()
The insertOne() operation in MongoDB allows you to insert a single document into a collection atomically. This means that either the entire document is successfully inserted, or no changes are made to the collection, maintaining consistency.
const { MongoClient } = require("mongodb");
const client = new MongoClient("mongodb://localhost:27017/myapp");
await client.connect();
const db = client.db("myApp");
const answer = await db.collection("office").insertOne({
name: "GFG",
age: 10
});
Success or Error
Success: Upon successful execution, the document is persisted in the database.
Error: In the event of an error, the operation is reverted, ensuring no alterations are made to the database.
Atomicity on the Document Level
MongoDB ensures atomicity at the document level, ensuring that all changes within a document operation are either fully committed or fully rolled back in case of failure. This prevents partial updates and data corruption.
Including Embedded Documents
Atomicity applies to operations involving embedded documents in a MongoDB document. When modifying or updating embedded documents, MongoDB ensures atomic changes, maintaining consistency throughout the document structure.
{
_id: ObjectId("userId"),
name: "GFG",
age: 10,
scores: [
{ team: "Technical Content Engineer", article: 23 },
{ team: "Python Developer", article: 12 }
]
}
Single Document Operations
MongoDB supports atomic operations on individual documents, ensuring that changes are either all applied or none.
db.collection.updateOne(filter, update, options);
Multi-Document Transactions
Starting from MongoDB 4.0, transactions allow you to perform several operations on multiple documents within a single transaction block. Transactions follow the ACID principles which means that if there is a failure, either all the operations within the transaction are fully committed or fully rolled back. This guarantees the consistency of the data.
session.startTransaction();
try {
// Perform multiple operations
session.commitTransaction();
} catch (error) {
session.abortTransaction();
throw error;
}
Step to Create a NodeJS App and Installing Module
Step 1: Create a NodeJS App using the below command:
npm init -y
cd foldername
Step 2: To work with MongoDB in NodeJS, install the mongodb package using npm:
npm install mongodb
The Updated Dependencies in your package.json file is:
"dependencies": {
"mongodb": "^4.0.0"
}
Example: Let's consider a scenario where we update the status of a document in a MongoDB collection:
JavaScript
const { MongoClient, ObjectId } = require('mongodb');
async function updateDocument() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('myapp');
const collection = database.collection('products');
const filter = {
_id: ("6642fba64176c633ad5c45ab"),
status: { $exists: false } // Only update if status doesn't exist
};
const update = { $set: { status: 'completed' } };
const options = {};
const result = await collection.updateOne(filter, update, options);
if (result.modifiedCount === 0) {
console.log(`Document not updated because status
field already exists or document with given _id not found.`);
} else {
console.log('Document updated successfully!');
}
} finally {
await client.close();
}
}
updateDocument();
Output:
Atomicity in MongoDB
Similar Reads
What is a collection in MongoDB? MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
4 min read
How to Listen for Changes to a MongoDB Collection? Tracking changes in MongoDB is essential for applications requiring real-time updates or synchronization with the database. Traditionally, this was achieved through polling, which could be inefficient. MongoDB offers more effective methods to track changes including Change Streams, the watch() metho
6 min read
How to Manage Data with MongoDB Effective data management is critical for the success of any application. MongoDB, a leading NoSQL database, offers a flexible and scalable solution for handling unstructured and semi-structured data. In this article, We will go through How To Manage Data with MongoDB by understanding its data model
4 min read
How do Change Streams Work In MongoDB? Change Streams in MongoDB allow applications to access real-time data changes without the complexity and overhead of polling the database. They provide a powerful and efficient way to listen to changes in collections, databases, or entire clusters. These are the following sub topics that we are goin
3 min read
How to Analyse and Monitor MongoDB Logs? Effective log management and monitoring are essential for ensuring the health, performance, and security of MongoDB databases. MongoDB generates logs that record key operations, events, and potential issues within the database, making it a vital tool for troubleshooting and performance optimizationI
5 min read
How to Enable Access Control & Authentication in MongoDB Securing our database is very important to protect our data. MongoDB, being one of the most popular NoSQL databases, provides robust security features like access control and user authentication to prevent unauthorized access and data breaches. Enabling authentication in MongoDB ensures that only au
6 min read
How to Deploy a Replica Set in MongoDB? MongoDB replica sets are crucial for ensuring high availability, fault tolerance, and data redundancy in MongoDB deployments. A replica set is a group of MongoDB instances that maintain the same dataset, offering a reliable solution for production environments.In this article, we will explain the pr
5 min read
MongoDB Cheat Sheet (Basic to Advanced) MongoDB is a powerful NoSQL database known for its flexible, document-oriented storage that is ideal for handling large-scale, complex data. MongoDB Atlas (a cloud-based solution), MongoDB Compass (a GUI for data visualization) and the MongoDB Shell for command-line operations, users can efficiently
11 min read
How to Back Up and Restore a MongoDB Database? MongoDB is considered one of the classic examples of NoSQL systems. Its documents are made up of key-value pairs, which are the basic unit of data in MongoDB. Whether we're dealing with accidental data loss, hardware failures, or other unforeseen issues, having a solid backup and restoration plan ca
5 min read
How to Create Database and Collection in MongoDB MongoDB is a widely used NoSQL database renowned for its flexibility, scalability, and performance in managing large volumes of unstructured data. Whether youâre building a small application or handling big data, MongoDB offers an easy-to-use structure for managing your data. In this article, we wil
6 min read