For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentIntroduction to Mongo DB

Introduction to Mongo DB

Published
05th Sep, 2023
Views
view count loader
Read it in
8 Mins
In this article
    Introduction to Mongo DB

    MongoDB, a highly scalable No-SQL database, is used for storing information in the form of JSON strings, where the structure of the table is not fixed (unlike in SQL database). So, the advantage here is that with the help of MongoDB, we can make quick changes in our entities without actually changing the database. 

    MongoDB is available in multiple variants and what you choose would depend on the type of development you are looking for. You can download and install the relevant server as per your operating system from here.  

    If you are already a Mongo user then you may have had the chance to work with the huge number of operations that Mongo provides for storing and retrieving information in a database.

    If you want to brush up the same before starting on this article, refer to the basics of MongoDB here. 

    In this article, we will learn about how we can use a MongoDB database with NodeJS.  

    But before do that, let’s delve a little into NodeJS. 

    Getting started with NodeJS  

    So what is Node JS, and why do we use it? 

    NodeJS is a backend JavaScript runtime environment that has become a favorite with developers and designers alike, due to the marvellous advantages it offers such as minimalism, speed, and compatibility with JavaScript. Not just individual programmers but world-class top tech companies around the world are using NodeJS as their backend tech stack because of the advantages it offers.   

    The beauty of NodeJs lies in the fact that it allows developers to write frontend abstractions with backend written in NodeJS. We will write our first NodeJS program here but before that, we have to install NodeJs, which is pretty straightforward. 

    Installing NodeJs Plugin for MongoDB:

    Follow these steps to install Node JS  

    • Install NPM (Node Package Manager).  

    The Node Package Manager) plugin is used to install various NodeJS plugins with a single command. 

    Double-check that you have npm installed in your system by simply running this command in your terminal: 

    $ npm -v[Text Wrapping Break]6.13.6  
    • Install the Node from NodeJs Website >> NodeJS  
    • See the type of Operation system and download the version as per your platform compatibility.  
    • Follow the installation guide as suggested by the installer.  
    • Check the node version by running this command in your terminal  
    $ node -v[Text Wrapping Break]v8.11.4  
    • If you have installed Node before NPM, you will probably need to update your NPM.  
    npm install npm@latest -g  

    Installing MongoDB Node.js Driver  

    The Mongo NodeJS driver allows us to interact with the MongoDB databases from NodeJs applications. To install MongoDB Node.js driver, run this command in your terminal.   

    npm install mongodb   

    To see the list of current drivers installed in the system, run the following command:  

    npm list mongodb  

    If you are stuck or have issues with installation of the drivers, then this official documentation is a good reference to go through.  

    Now that we are ready with both the database and NodeJS backend, let’s move ahead and create a simple NodeJs project. The aim of this project is to insert and retrieve information from the database. 

    Using Node.JS to connect to MongoDB database   

    To do this, we will write a simple Node.js script which will connect to our database. And then we will perform an operation to list all the databases in our cluster.

    Introduction to Mongo DB

    Cluster? What is a cluster?

    A cluster is nothing but a set of nodes that carry the copies of your database. At a high level, you can say, your database is stored inside a cluster. To work on databases with Node, the easiest way is to use Atlas service which is MongoDB’s fully-managed database. If you are still unfamiliar with these terms, you can go through the complete documentation here   

    Connecting MongoDB

    Now that we have all our installations in place, let’s get started with connecting our database from NodeJs. Let’s Code! 

    We will begin with Importing the Mongo Client as shown below: 

    const {MongoClient} = require('mongodb');  

    To connect to the MongoDB database we have to import the MongoClient class from the MongoDB module, the instance of which can be used to connect to the cluster or for accessing the database from that cluster. 

    Next step is to use a Main() function, where we can call other functions and can get connected to MongoDB cluster. 

    const uri = "mongodb+srv://<put-your-username>:<put-your-password>@<write-your-cluster-url>/test?retryWrites=true&w=majority";   

    Note: You need to update your password and username for the user. 

    Now that we are ready with our URI, create an instance of MongoClient as below: 

    const client = new MongoClient(URI);  

    Your instance is ready, so now you can use MongoClient to connect to the cluster by calling client.connect() as below:  

    await client.connect();  

    We have used the await keyword so as to ensure that it blocks any further execution until our operation is completed. 

    And that’s it. We are ready to interact with our database. Let’s try it out by simply printing the list of all the databases in our cluster.  

    await listAllDatabases(client);  

    You can put any name to the above function. 

    The next step is to finally put all the functions together and wrap them in a try/catch block in order to handle any errors. 

    try   await client.connect();   await listAllDatabases(client);catch (e) {    console.error(e);}  

    And, close the connection as below:  

    finally { await client.close(); }  

    No, let’s put everything together and call our main function() as:  

    async function main(){ const uri = "mongodb+srv://<your-username>:<your-password>@<your-cluster-url>/test?retryWrites=true&w=majority"; const client = new MongoClient(uri); try {// Connect to the MongoDB cluster await client.connect(); // Here make the DB calls or some operations await  listAllDatabases(client);  catch (e) {    console.error(e); } finally { await client.close();  Break]main().catch(console.error);  //To see if there are aby errors

    Let’s use our function “listAllDatabases” to list all the databases in our cluster.  

    async function listAllDatabases(client){  databasesList = await client.db().admin().listAllDatabases(); console.log("Databases List Is:");[Text Wrapping Break]    databasesList.databases.forEach(db => console.log(` - ${db.name}`));};  

    If you can’t wait to see your output, then all that is left to do is to save it. Save your file as list.js.  

    Time to execute the NodeJs script. Let’s execute the script by running the following command in our terminal:  

    (Ensure that the server is running and up!) 

    node list.js  

    The output should come as below:  

    Databases: - data_books - data_gates - data_houses - data_nodes- data_tables- admin - local  

    Now that we are running with the database, let’s see the different data types they are supported on.  

    Mongo DB data types

    Have you heard of BSON? BSON is a binary-encoded format of JSON. Documents in MongoDB are stored in the format of BSON. Here is a list of typically used data types supported by MongoDB: 

    • String − It is used to store the data. It should be UTF-8 valid. 
    • Integer − This data-type is used to store a numerical value. Depending on our server, Integer can be either of 32 bit or 64 bit. 
    • Boolean − To store a boolean (true/ false) value we use this type of data type. 
    • Double − Used for storing floating-point values. 
    • Arrays − This type of data-type is used for storing list or arrays. 
    • Timestamp - This type of data-type is used to check if an element has been modified or added. 
    • Min/ Max keys − We can use min or max data types for comparing the value against the lowest and highest BSON elements and vice-versa. 
    • Object − This data type stores embedded documents. (A document that contains another document in the form of the key-value pair) 
    • Null − This type of data-type is used by MongoDB to store a Null value. 
    • Symbol − It is not supported by a shell, but if it gets a symbol from the database, it is converted into a string. So it’s quite identical to a string data type. 
    • Regular expression − These MongoDB data types stores regular expressions in MongoDB. It maps directly to JavaScript Regular Expression. 
    • Date −  This type of data-type is used to store the date or time. We can also use our date or time by simply creating an object of Date and passing elements like day, month, year into it. 
    • Object ID − Mongo uses this type of datatype to store the document’s ID. 
    • Binary data − Typically used to store binary data. 

    Mongo DB and Collections

    A database can have multiple collections. A collection is a table that contains all your documents. We can create a collection as follows:  

    const collection = db.createCollection(name, options), or 
    const collection = db.collection(‘books’);    
    

    where, 

    • name is the connection name which can be anything, 
    • The option is a configuration document used for specifying the collection and is optional. 
    • We can list the following options while creating a collection: capped, autoIndexId, max, and size. 
    • createCollection() is an inbuilt method in MongoDB, which is used to create a new collection in database as shown above. 

    Note: In MongoDB, a collection is never created until it gets some content!  

    db.collection('check', {strict:true}, function(err, collection) {});  
    

     So, this code will never create a collection until and unless you specify and insert it in the document.  

    Conclusion

    Today we learnt the basics of MongoDB, and how and why MongoDB is compatible with NodeJS. We also looked at how we can connect to our MongoDB database from NodeJS script, and found a cool demo of listing out the names of all the databases in our cluster. There are many activities that we can do with NodeJS in our database which involves the basic CRUD operations like insert, update, remove, or making a query in our collection.  

    And if you get stuck, see the official documentation of all of them here. It has plenty of features that make our job easier.  

    Happy Learning! :)

    Profile

    Bala Krishna Ragala

    Blog Author

    Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon