Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

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

Example of directing a write operation to the primary:

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

Secondary

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?

Other Common MongoDB Performance Questions (and Answers)

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost