0
0
MongodbConceptBeginner · 3 min read

Primary and Secondary in MongoDB: Roles Explained Simply

In MongoDB, primary is the main server that handles all write operations and reads by default, while secondary servers replicate data from the primary to provide redundancy and support read operations. This setup ensures data availability and fault tolerance in a replica set.
⚙️

How It Works

Imagine a library where one librarian (the primary) is responsible for adding new books and updating records. Other librarians (the secondaries) watch the primary closely and copy every change to their own shelves. If the primary librarian is unavailable, one of the secondaries can step up to keep the library running smoothly.

In MongoDB, the primary node accepts all writes and replicates these changes to secondary nodes. Secondary nodes keep copies of the data and can serve read requests if configured. This system helps keep data safe and available even if one server fails.

💻

Example

This example shows how to check the current primary and secondary nodes in a MongoDB replica set using the MongoDB shell.

shell
rs.status()
Output
{ "set" : "rs0", "members" : [ { "_id" : 0, "name" : "mongo1:27017", "stateStr" : "PRIMARY" }, { "_id" : 1, "name" : "mongo2:27017", "stateStr" : "SECONDARY" }, { "_id" : 2, "name" : "mongo3:27017", "stateStr" : "SECONDARY" } ] }
🎯

When to Use

Use a primary-secondary setup in MongoDB when you want to ensure your data is safe and your application stays online even if one server fails. The primary handles all writes, so it is best for operations that change data. Secondaries are useful for backup and can also handle read requests to reduce load on the primary.

For example, an online store uses a primary to process orders and secondaries to serve product catalog reads and backups. This way, customers get fast responses and the store never loses data.

Key Points

  • The primary node handles all writes and replicates data to secondaries.
  • Secondary nodes keep copies of data and can serve reads if configured.
  • Replica sets improve data availability and fault tolerance.
  • If the primary fails, a secondary can be elected as the new primary automatically.

Key Takeaways

Primary node handles all writes and replicates data to secondaries.
Secondary nodes keep copies and can serve reads to reduce primary load.
Replica sets ensure data availability and fault tolerance.
Automatic failover promotes a secondary to primary if needed.