What is Atomicity in MongoDB and How to Achieve it?

Atomicity ensures that all changes within a single operation are either fully completed or not applied at all, preventing data corruption and inconsistencies.

Table of Content

  • Atomicity and How to Achieve it
  • Operation Example: insertOne()
  • Success or Error
  • Atomicity on the Document Level
  • Including Embedded Documents
  • Single Document Operations
  • Multi-Document Transactions

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



Contact Us