Table of contents
1.
Introduction
2.
What is MongoDB Cluster?
3.
MongoDB Cluster Architecture
4.
Setting Up MongoDB Cluster with Node.js and Express
5.
Implementing MongoDB Cluster with Node.js and Express
5.1.
Output
5.2.
Explaination
6.
Key Features of MongoDB Cluster
7.
Frequently Asked Questions:
7.1.
What is MongoDB Cluster?
7.2.
How does MongoDB Cluster ensure high availability?
7.3.
How can I set up MongoDB Cluster with Node.js and Express?
7.4.
What are the key features of MongoDB Cluster?
7.5.
How does MongoDB Cluster ensure fault tolerance?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

MongoDB Cluster

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Do you want to learn more about MongoDB Cluster and how it may improve your database working with Node.js and Express? Not to worry, this detailed article walks you through the architecture of MongoDB Cluster, its implementation using Node.js and Express, and the essential characteristics that make it a dependable solution for high availability and scalability. We also try to implement using a real cluster of MongoDB.

Introduction

What is MongoDB Cluster?

First, understand MongoDB. MongoDB is a non-relational database, cross-over platform, document-oriented database that provides high performance, high availability, and easy scalability. MongoDB works on the concept of collection and documentation. MongoDB is built on a scale-out architecture that

MongoDB

 has become popular with developers of all kinds for developing scalable applications with evolving data schemas. As a document database, MongoDB makes it easy for developers to store structured or unstructured data. MongoDB stores data in JSON.

MongoDB Cluster is a distributed database design that allows for horizontal scaling of MongoDB databases across multiple servers or nodes. It is a very much used database throughout the world. Even in MERN Stack M stands for MongoDB.  It gives high availability, fault tolerance, and automatic data sharding. With MongoDB Cluster, you can effectively handle large-scale databases and ensure seamless scalability for your applications.

MongoDB Cluster Architecture

The design of MongoDB Cluster:

Replica Sets: A replica set has multiple nodes, including a main and one or more secondary nodes. The primary node handles all write processes, whereas secondary nodes replicate data from the primary node. And the thing is, if the primary node fails, one of the secondaries immediately becomes the new primary, ensuring continuous availability. Isn't it amazing?

Sharding: Sharding includes distributing data across multiple shards, which are individual MongoDB instances. Every shard includes a subset of the data, which allows for efficient distribution and scalability. Here you will get a key so where ever data is spread among the shards.

Setting Up MongoDB Cluster with Node.js and Express

To set up MongoDB Cluster with Node.js and Express, follow these steps:

  1. Install the required dependencies: Use npm or yarn to install the MongoDB driver for Node.js and Express.
     
  2. Define the MongoDB Cluster connection string: Obtain the connection string from your MongoDB Cluster provider or set up your own cluster. Replace <username>, <password>, and cluster-url with your credentials and cluster URL.
Connect to the MongoDB Cluster
Connect to the MongoDB Cluster
Connect to the MongoDB Cluster
Connect to the MongoDB Cluster

3. Connect to the MongoDB Cluster: You can use the Mongodb Client to connect with MongoDB cluster.
 

Connect to the MongoDB Cluster

4. Access databases and collections: Once connected, use the string that is given while creating a cluster and connect with it.
 

5. Perform database operations: Now, you can create a schema or model and perform CRUD operations.
 

Implementing MongoDB Cluster with Node.js and Express

const express = require("express")
app=express();
const dotenv = require('dotenv');
const mongoose=require('mongoose');
const cors= require('cors');
const { response, urlencoded } = require('express');


//cors configuration
app.use(cors());

//For taking data with json api
app.use(express.json({limit: '100mb', extended: true}),)

//Setting .env file
dotenv.config({path:'./.env'});
const port = process.env.LOCAL_PORT_NAME;
const hostname= process.env.LOCAL_HOST_NAME;

//Connecting Mongo Db

mongoose.set('strictQuery', false);
mongoose.connect(process.env.MONGO_DB_URL,{ useNewUrlParser: true }).then((response)=>{
    console.log("Connected MongoDb")
}).catch((err=>{
   console.error(err)
   process.exit(1);

}));

//Displaying news content in the output
app.get('/', (request, response) => {

    response.send(`connected`)
   
});

//Fetching
app.listen(port,hostname, () => {
    console.log(`Server started`);
});


In the env File add cluster string:

#You can set any host name you want and port as per you but make sure it should not be using write now.
LOCAL_HOST_NAME=127.0.0.1
LOCAL_PORT_NAME=5000
# MONGO_DB string with password
MONGO_DB_URL=mongodb+srv://akscrv:PassNinja@website-ninja.zu1fttc.mongodb.net/?retryWrites=true&w=majority

 

Run the Code using 

npm start

Output

Output

Explaination

In the above code it simply setting up a Node.js and Express server. And also we have connected with a MongoDB Cluster. It imports the necessary libraries, initlize the Express programme, and defines the port. When you will be creating cluster thay will give you string for connection. After that you will be able to perform database operations within the Express app once it is linked.

Key Features of MongoDB Cluster

The following are the key features of the MongoDB Cluster:

  • MongoDB Cluster has many characteristics that make it a formidable database management option.
     
  • Automatic failover: If a node fails, MongoDB Cluster quickly run a backup node to the primary role, providing uninterrupted availability.
     
  • Data sharding allows us to divide data across several shards, allowing for horizontal scaling and effective data storage.
     
  • Horizontal scalability: as more nodes are added, the MongoDB database scales up to meet higher workloads and larger datasets.
     
  • Replica sets provide data redundancy by retaining several copies of data across separate nodes, boosting fault tolerance and data reliability.
     
  • Load balancing: MongoDB Cluster automatically balances read operations between replica set members, optimising performance and ensuring that requests are distributed evenly.

Frequently Asked Questions:

What is MongoDB Cluster?

MongoDB Cluster is a distributed database architecture that enables horizontal scaling of MongoDB databases to multiple servers or nodes. It make sure it is high availability, fault tolerance, and automatic data sharding.

How does MongoDB Cluster ensure high availability?

MongoDB Cluster achieves high availability through replica sets. Each replica set is of multiple nodes, and also it includes a primary and one or more secondaries. In case of a primary node failure, one of the secondaries automatically becomes the new primary, ensuring continuous availability.

How can I set up MongoDB Cluster with Node.js and Express?

It is very easy to set up MongoDB Cluster with Node.js, and Express involves connecting to the cluster using the MongoDB driver for Node.js, accessing databases and collections, and performing database operations within your Express application.

What are the key features of MongoDB Cluster?

MongoDB Cluster offers many features like automatic failover, data distribution with sharding, horizontal scalability, data redundancy through replica sets, load balancing, and support for geographically distributed deployments.

How does MongoDB Cluster ensure fault tolerance?

MongoDB Cluster make sure of fault tolerance by distributing data across multiple nodes and maintaining multiple copies of data using replica sets. 

Conclusion

In this article we explored Mongodb Cluster, its architecture and demonstrated its implementation with Node.js and Express. Now you are aware of the power of MongoDB Cluster, along with the simplicity and flexibility of Node.js and Express.

Check out below this article and learn more about it.

Also, you can check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive Programming, etc., as well as some Contests and more Interview Experiences curated by top Industry Experts only on  Coding Ninjas Studio.

Live masterclass