Transaction lock in MongoDB?

In MongoDB versions prior to 4.0, native transactions weren't available. To implement transaction-like locking behavior, you can use findOneAndUpdate() with a lock field to ensure atomic operations on documents.

Syntax

db.collection.findOneAndUpdate(
    { "lock_field": { "$exists": false } },
    { "$set": { "lock_field": true } }
)

Sample Data

db.demo404.insertMany([
    { "FirstName": "John" },
    { "FirstName": "Robert" },
    { "FirstName": "Mike" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e6f8c38fac4d418a0178592"),
        ObjectId("5e6f8c3cfac4d418a0178593"),
        ObjectId("5e6f8c40fac4d418a0178594")
    ]
}

Display all documents from the collection ?

db.demo404.find();
{ "_id": ObjectId("5e6f8c38fac4d418a0178592"), "FirstName": "John" }
{ "_id": ObjectId("5e6f8c3cfac4d418a0178593"), "FirstName": "Robert" }
{ "_id": ObjectId("5e6f8c40fac4d418a0178594"), "FirstName": "Mike" }

Example: Implementing Document Lock

Use findOneAndUpdate() to atomically lock the first available document ?

result = db.demo404.findOneAndUpdate(
    { "in_transaction": { "$exists": false } },
    { "$set": { "in_transaction": true } }
);
{ "_id": ObjectId("5e6f8c38fac4d418a0178592"), "FirstName": "John" }

Verify the lock was applied ?

db.demo404.find({ "_id": ObjectId("5e6f8c38fac4d418a0178592") });
{ "_id": ObjectId("5e6f8c38fac4d418a0178592"), "FirstName": "John", "in_transaction": true }

How It Works

  • findOneAndUpdate() performs an atomic operation ? find and update in a single step.
  • The query { "in_transaction": { "$exists": false } } finds documents without a lock.
  • Only one document gets the lock, preventing race conditions between concurrent operations.
  • The operation returns the original document before the update was applied.

Conclusion

Use findOneAndUpdate() with a lock field to simulate transaction behavior in older MongoDB versions. This approach provides atomic document-level locking to prevent concurrent modification conflicts.

Updated on: 2026-03-15T02:52:31+05:30

727 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements