MongoDB

Understanding Transactions and Replication in MongoDB

Understanding Transactions and Replication in MongoDB

Transactions in MongoDB

What are Transactions?

  • Transactions allow you to execute multiple operations in an atomic, all-or-nothing manner. They ensure data consistency and integrity.

ACID Transactions:

  • Atomicity: All operations within a transaction are completed, or none are.
  • Consistency: Data transitions from one valid state to another.
  • Isolation: Transactions operate independently without interference.
  • Durability: Once a transaction is committed, it remains committed.

Multi-Document Transactions:

//Starting a Transaction
> const session = db.getMongo().startSession();
> const orders = session.getDatabase("myDatabase").orders;
> session.startTransaction();

//Committing a Transaction
> orders.insertOne({ item: "Laptop", quantity: 1 });
> session.commitTransaction();

//Aborting a Transaction
> session.abortTransaction();

Replication in MongoDB

What is Replication?

  • Replication ensures data availability and fault tolerance by duplicating data across multiple servers.

Replica Sets:

  • A replica set is a group of MongoDB servers that maintain the same data set. One member acts as the primary node, while others are secondary nodes.
//Setting Up a Replica Set
> rs.initiate({
    _id: "myReplicaSet",
    members: [
      { _id: 0, host: "localhost:27017" },
      { _id: 1, host: "localhost:27018" },
      { _id: 2, host: "localhost:27019" }
    ]
  })

Understanding Replica Set Operations:

  • Primary Node: Receives all write operations.
  • Secondary Nodes: Replicate data from the primary and can serve read requests.

Failover and Recovery:

  • Automatic Failover: If the primary node fails, a secondary node is automatically promoted to primary.
  • Manual Failover: Force a failover by stepping down the primary.
> rs.stepDown()

MongoDB transactions, MongoDB ACID transactions, MongoDB replica sets, MongoDB replication setup, MongoDB failover, MongoDB data consistency.

Leave a Reply

Your email address will not be published. Required fields are marked *