What is “Atomicity” in MongoDB

What is “Atomicity”?

In database systems, “atomicity” refers to the all-or-nothing nature of transactions. If a transaction consists of multiple operations, either all of them are executed successfully, or none of them are, ensuring the database remains in a consistent state.

Operation Example: insertOne()

Consider the insertOne() operation in MongoDB, which inserts a single document into a collection:

const { MongoClient } = require("mongodb");

const client = new MongoClient("mongodb://localhost:27017");
await client.connect();
const db = client.db("testDB");

const result = await db.collection("students").insertOne({
name: "John",
age: 21
});

Success or Error

  • Success: If the operation succeeds, the document is saved in the database.
  • Error: If an error occurs, the operation is rolled back, meaning no changes are made to the database.

Atomicity on the Document Level

MongoDB guarantees atomicity at the document level. This means that CRUD operations (Create, Read, Update, Delete) are atomic for individual documents. If an operation targets a single document, either all the changes are applied, or none are.

Including Embedded Documents

The atomicity extends to embedded documents within a single document. If you have a document with embedded documents, MongoDB ensures that operations affecting the parent document and its embedded documents are atomic.

{
_id: ObjectId("someId"),
name: "John",
age: 21,
scores: [
{ subject: "Math", grade: 85 },
{ subject: "History", grade: 92 }
]
}

For example, if you’re updating both the age field and an element in the scores array, MongoDB will ensure that both changes are applied atomically.

await db.collection("students").updateOne(
{ _id: ObjectId("someId") },
{
$set: {
"age": 22,
"scores.0.grade": 86
}
}
);

If this operation encounters an error, none of the changes — neither the age update nor the scores update—will be applied, maintaining data consistency.

Summary

Atomicity in MongoDB ensures that CRUD operations are all-or-nothing at the document level, providing a guarantee for data integrity. This atomicity extends to embedded documents within a single parent document.

,