Question: What is the difference between a primary and secondary in MongoDB?

Answer

In MongoDB, replication is the process of synchronizing data across multiple servers. A replication set is a group of MongoDB server instances that maintain the same data set. Within a replica set, there are two types of nodes: primary and secondary.

Primary

  • The primary node is the main write node of the replica set.
  • All write operations are directed towards the primary node.
  • It records all changes to its data sets in an operation log (oplog), which is a special capped collection.
  • After performing the write operations, the primary node replicates these changes to the secondary nodes using the oplog.
  • There can only be one primary node at any given time in a replica set.

Example of directing a write operation to the primary:

db.collection.insertOne({ name: 'John Doe', age: 28 });

Secondary

  • Secondary nodes replicate the oplog from the primary and apply the changes to themselves in an asynchronous process.
  • By default, secondary nodes are read-only but can be configured to accept read operations from clients by setting readPreference to secondary.
  • Secondary nodes can also participate in elections to choose a new primary if the current primary becomes unavailable.
  • You can have one or more secondary nodes in a replica set.

Example of setting readPreference to read from secondaries:

db.collection.find().readPref('secondary');

Key Differences

  1. Role in Replication: The primary node is responsible for all write operations, while secondary nodes replicate data from the primary and can serve read operations.
  2. Election: In the event of a primary failure, one of the secondary nodes can be elected as the new primary.
  3. Write Availability: Writes can only happen on the primary node.
  4. Read Scalability: Secondary nodes can increase the read scalability of your application by serving read requests.

Understanding the roles and differences between primary and secondary nodes in MongoDB is crucial for designing robust, scalable, and highly available applications.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.