Skip to content

MongoDB Atomic Operations

In MongoDB, atomic operations are operations that are completed in a single operation, either fully successful or fully failed. MongoDB supports various atomic operations, which can help us ensure data consistency.

Basic Concepts

Types of Atomic Operations

  1. Document-Level Atomic Operations: Atomic operations performed on a single document.
  2. Collection-Level Atomic Operations: Atomic operations performed on a single collection.
  3. Database-Level Atomic Operations: Atomic operations performed on a single database.

Characteristics of Atomic Operations

  1. Atomicity: The operation is either fully successful or fully failed.
  2. Consistency: After the operation is completed, the state of the data is consistent.
  3. Isolation: The operation is not affected by other operations.
  4. Durability: After the operation is completed, the state of the data is persistent.

Document-Level Atomic Operations

Update Operations

javascript
// Update a single document
db.users.updateOne(
  { _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") },
  { $set: { age: 31 } }
)

// Update multiple documents
db.users.updateMany(
  { status: "active" },
  { $set: { status: "pending" } }
)

Array Operations

javascript
// Add an element to an array
db.users.updateOne(
  { _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") },
  { $push: { tags: "tech" } }
)

// Remove an element from an array
db.users.updateOne(
  { _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") },
  { $pull: { tags: "tech" } }
)

// Replace an element in an array
db.users.updateOne(
  { _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") },
  { $set: { "tags.0": "new" } }
)

Increment Operations

javascript
// Increment operation
db.users.updateOne(
  { _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") },
  { $inc: { age: 1 } }
)

Collection-Level Atomic Operations

Insert Operations

javascript
// Insert a single document
db.users.insertOne({
  name: "John",
  age: 30,
  email: "john@example.com",
  status: "active"
})

// Insert multiple documents
db.users.insertMany([
  {
    name: "Jane",
    age: 25,
    email: "jane@example.com",
    status: "pending"
  },
  {
    name: "Bob",
    age: 35,
    email: "bob@example.com",
    status: "inactive"
  }
])

Delete Operations

javascript
// Delete a single document
db.users.deleteOne({ _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") })

// Delete multiple documents
db.users.deleteMany({ status: "pending" })

Database-Level Atomic Operations

Transaction Operations

In MongoDB 4.0 and later versions, we can use transaction operations to perform atomic operations on multiple operations.

javascript
// Start a transaction
const session = db.getMongo().startSession()
session.startTransaction()

try {
  // Execute operations
  db.users.insertOne({
    name: "John",
    age: 30,
    email: "john@example.com",
    status: "active"
  }, { session })

  db.orders.insertOne({
    userId: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f"),
    product: "iPhone X",
    price: 999,
    quantity: 1
  }, { session })

  // Commit the transaction
  session.commitTransaction()
} catch (error) {
  // Rollback the transaction
  session.abortTransaction()
  console.error(error)
} finally {
  // End the session
  session.endSession()
}

Best Practices for Atomic Operations

Use Document-Level Atomic Operations

For most scenarios, we should use document-level atomic operations because document-level atomic operations have higher performance and are simpler.

Use Transaction Operations

For scenarios that require multiple operations, we should use transaction operations to ensure the atomicity and consistency of the operations.

Avoid Complex Operations

We should avoid using complex operations because complex operations may cause performance degradation.

Summary

In MongoDB, atomic operations are operations that are completed in a single operation, either fully successful or fully failed. MongoDB supports various atomic operations, including document-level atomic operations, collection-level atomic operations, and database-level atomic operations. For most scenarios, we should use document-level atomic operations; for scenarios that require multiple operations, we should use transaction operations. At the same time, we should also avoid using complex operations to ensure the performance and consistency of the operations.

Content is for learning and research only.