Introducing Dragonfly Cloud! Learn More

Question: How does MongoDB handle the concept of master and slave nodes in a cluster?

Answer

MongoDB, a popular NoSQL database, uses a distributed architecture to manage data. However, the terminology 'master' and 'slave' has been replaced by more inclusive language within the MongoDB ecosystem and many others in tech. The terms now used are 'Primary' and 'Secondary' respectively.

Primary and Secondary Nodes

In a MongoDB cluster, which is part of a replica set configuration, one node acts as the Primary node (formerly known as 'master'), and the other nodes act as Secondary nodes (formerly known as 'slaves'). The Primary node receives all write operations, while Secondary nodes replicate the data from the Primary to maintain data redundancy and availability.

Automatic Failover

One of the key features of MongoDB's replica set is the automatic failover mechanism. If the Primary node fails, one of the Secondary nodes is automatically elected to become the new Primary. This ensures that the database remains available for both read and write operations even in the case of node failures.

Read and Write Operations

Clients usually perform write operations on the Primary node. However, for read operations, clients can configure their MongoDB driver to read from either the Primary only, or they can include Secondary nodes to distribute the read load. Reading from Secondaries can help in reducing the load on the Primary node and achieve more scalable read throughput.

// Example code to connect to a MongoDB replica set and specify read preference
const { MongoClient } = require('mongodb');

const uri = 'mongodb://user:password@primaryHost:port,secondaryHost1:port,secondaryHost2:port/?replicaSet=myReplicaSet';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

client.connect(err => {
  if (err) throw err;

  // Specify the read preference
  const collection = client.db('test').collection('data', { readPreference: 'secondaryPreferred' });
  
  // Perform a read operation
  collection.find({}).toArray((err, docs) => {
    if (err) throw err;
    console.log(docs);
    
    // Close the connection
    client.close();
  });
});

Conclusion

In a MongoDB cluster, the primary-secondary architecture ensures data consistency, high availability, and fault tolerance. Through the election process, MongoDB ensures that the database service remains uninterrupted even during node failures, making it a robust choice for applications requiring high availability.

Was this content helpful?

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

Start building today 

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