Mongo DB is the NoSQL database system of MERN stack development course family that uses collection and documents unlike SQL. In this blogpost by a trainer of our MERN stack development course, you’re going to learn how to use MongoDB from complete scratch and we will to show you how to install MongoDB on your windows computer locally and interact with it using the shell and compass.
What Is MongoDB?
It’s a no SQL database management system that can manage a humongous amount of data and it’s becoming increasingly popular and favored by many big tech companies.
It’s a database that we use to store data any type of data. For example: whether it can be ‘user data’ for your website or ‘blog data’ for a blog site or something else. But we will learn a bit more about the type of database that MongoDB is and this makes it different from other databases. So first of all, MongoDB is a NoSQL database meaning that we don’t use SQL commands to interact with it. One such SQL database you have probably heard of is MySQL and a NoSQL database like MongoDB is very different from something like that.
Difference between MongoDB vs SQL database
SQL databases or relational databases are made up of tables with rows and columns, where each table is used to store a specific data type like users or blog posts. Each row in a table is essentially a record of other data types stored in that table. Each column is a property on that particular record like a username, an email, a name, an agenda, an id, etc. So, you can see how data is stored in tables this way. Sometimes, our different data types and data tables can be related to one another.
For example: We might have an ‘author record’ stored in one table and ‘book records’ in another. These are two different types of data but they could be related to each other. We might form a relationship between the two tables. For explanation, we can understand it in this way.
One ‘author’ might have many books and we’d have a one-to-many relationship between those tables. To query these SQL databases, we use SQL commands that look something like ‘SELECT*FROM author’ which means this particular command would fetch all the records from the author’s table.
Now, a NoSQL database like MongoDB is very different from a SQL database because instead of tables, columns, and rows it uses collections and documents. This time each collection in a NoSQL database would store a specific type of data record like users, authors, books, or something else entirely, and in NoSQL terminology these records inside collections are called documents. They look very much like JSON objects with key-value pairs and this structure can have a few benefits over using tables, rows, and columns.
Advantages of MongoDB, why is it preferred by developers and companies?
Firstly, it’s much easier to work with this if you’re used to something like JavaScript because documents in MongoDB are very much like JSON or JavaScript objects.
Secondly, it allows us to store nested documents within a document. For example, a document in the ‘books collection’ could have an author property and the author property could be a document in itself which has a ‘first name property’, a ‘last name property’, and ‘an age property’. This would be an alternative to the approach of using two different tables in an SQL database to store those two data types separately. You could also have two separate collections for those data types in MongoDB.
But we get this option of nested documents which is sometimes a better option. It allows the structure of our data to be a little bit more flexible and also depending on your coding background, querying and NoSQL database could be easier too. This is especially the case with MongoDB which makes it easy to use simple methods to write and read data to and from the database. On top of that, it has got high-speed performance which makes it quick to make and handle those queries.
How to Install MongoDB for Windows PC?
- Go to the website “mongodb.com” and then hover over to resources and server. On the left sidebar, go to installation. Here’s a list of different installation tutorials depending on your operating system.
- We’ll select Windows. Let’s scroll down and look for “install MongoDB Community Edition”.
- All you have to do is follow the below steps from beginning. We will go to the “download Centre” and will open this in a new tab.
- Select the current version and your platform.
- Select your OS and the installation package. We’ll keep the package same and download.
- Pick a place to save the installer. For now, we are keeping it default but can you choose your own Location.
- Open the file when it’s done and click next.
- Accept the license agreement and install mongo as a service.
- Make sure that the box is checked. After that, Be sure to install the “MongoDB compass program” which is defined as a graphical user interface for managing our database. Give it a couple of minutes.
- MongoDB is installed this way and we can hit “finish”.
- You just have to open the compass and establish a connection by hitting the green connect button.
How to install the MongoDB shell?
- To install the shell, we’re going to go to the left sidebar and click on “MongosH” on the same website we had visited before.
- Go to the “download Centre” and select the “current version” and “platform” of usage.
- Hit the “Download button” and open when it’s done.
- We will unzip the folder by right clicking on it and choose “extract all”.
- All we will need is the file path. Let’s open this folder, go to bin.
- Right click on executable and go to properties.
- Copy the file location and it should be within the bin folder and then, we’re going to add that file path to our environment variables.
- Search for “environment variables” in search bar.
- Within system properties, go to the advanced tab and click on environment variables.
Underneath system variables, delete the existing “MongoSH” file and click new and come up with a variable name.
Paste that file location and hit okay and close. So, if we go to that folder and open the executable, MongoDB shell will be going to be opened.
Let us learn about the basic concepts of MongoDB.
Database, Collections and Documents
Before, we get into interacting with MongoDB, we will quickly talk about how data is structured in MongoDB.
MongoDB stores data inside ‘collections and a ‘database’ can have as many ‘collections’ as you like for different types of data.
For example, a database could have three collections “a user’s collection”, “a blog post collection”, and “a comments collection”. The user collection would store “user data” or “user documents”, the blog post collection would store “blog posts” and there would be documents also and the “comments collection” would store “comment documents”. Different types of data or documents are stored together in their own groups or their own collections. This way, it would be easy to fetch all of the documents from a single collection.
For example, we might want to fetch a list of all of the ‘blog post documents.’ So, we can output the title of each one in the browser on my website. We would just tell MongoDB to send me all the documents inside the ‘blog posts collection’.
‘Documents’ themselves represent the ‘individual records’ in a specific ‘collection’. For example, inside the blog posts collection, we’d store a lot of blog post documents and each one represents a single blog post.
The way that data is structured inside a ‘document’ looks very much like a JSON object with ‘key value pairs. But actually, it’s being stored as BSON which is just binary JSON. For all intents and purposes a document looks very much like a JSON object and when we fetch documents from a collection, JSON objects are ultimately what we get back.
A “blog post document” might look something like this object with a “title” property which could be a string value, an “author property” which could also have a string value, a “tags property” which could be an array of strings, an “upvotes property” which could be an integer and a “body property” which would also be a string.
Like these custom properties that we might give to blog post objects, every document would also have a “unique id property” to identify them. This property would be a “special object id” type in MongoDB and it’s assigned to the document by MongoDB itself when we create a document. So that every document can be identified by this “unique id value” and then if you wanted to, you could query MongoDB to fetch your document with that specific id.
So, you can see how these documents look very much like JSON objects and that makes the data really easy to work with.
Documents can have properties whose values themselves can also be documents or arrays of documents. In this case we’d call those documents “nested documents”
For example: the “author property” could actually be a nested document which has a “first name property”, “an email property” and “a role property” or something. This would be an alternative approach to referencing “an author document” in another collection.
CRUD Operation in Mongodb
This is one of the most important part of whatever we learn in MongoDB. We will be totally focused about the CRUD Operation which stands for CREATE, READ, UPDATE, AND DELETE.
MongoDB is very small and there are not gigantic and numerous things you can do with.
- Create: Creating document involves adding new records to collection.
- insertOne (data, options): This is used to just enter one specific data to a collection in MongoDB.
db.collection.insertOne ({
name: "Laila",
age: 30,
city: "New Delhi"
});
- insertMany(data, options): This operation is used to add a collection of data.
For example: If you want to register five students at a time in your database, you can do this with the help of this operation.
db.collection.insertMany([
{ name: "Baba", age: 55, city: "Kerla" },
{ name: "Charlie", age: 35, city: "Chicago" }
]);
- Read: The Read operations are used to retrieve documents from the collection. Read operation is heavily for the analytic guys. It has got two major operations under it.
- Find (filter, options): It retrieves the document matching the specific query criteria.
For example:
// Retrieve all documents
db.collection.find();
// Retrieve documents matching a condition
db.collection.find({ age: { $gt: 55 } });
// Retrieve specific fields
db.collection.find({}, { name: 1, _id: 0 });
- findOne (filter,options): findOne doesn’t return only specific data but returns the first thing which matches the criteria or matches the filter while looking up into the database. There might be other data matching the crieteria, but it will be going to return only the first one.
For example:
db.collection.findOne({ name: "Baba" });
- Update: This operation involves the modifications in existing records.
- updateOne(filter,data,option): updates a single document that matches the filter criteria.
For example:
db.collection.updateOne(
{ name: "Baba" },
{ $set: { age: 131 } }
);
- updateMany(filter,data,option): Updates multiple documents that match the filter criteria.
For example:
db.collection.updateMany(
{ city: "New Delhi" },
{ $set: { city: "San Francisco" } }
);
- replaceOne(filter,data,option): Replaces a single document that matches the filter criteria with a new document.
For example:
db.collection.replaceOne(
{ name: "Baba" },
{ name: "Kaka", age: 26, city: "San Diego" }
);
- Delete: This operation involves the removal of records from the collection.
- deleteOne(filter,Options): Deletes a single document(which is going to the first one) that matches the filter criteria.
For example:
db.collection.deleteOne({ name: "XYZ" });
This command deletes the first document that matches the name "XYZ."
- deleteMany(filter,Options ): Deletes multiple documents that match the filter criteria.
db.collection.deleteMany({ city: "ABC" });
Sorting and limiting data:
We know, when we send queries to MongoDB to fetch data, we use the ‘find’ method or the ‘findOne’ method to find whatever document we want. Now, we will try on some other methods to perform additional tasks that is sorting data and limiting the number of documents that we get back as output.
Sorting Data
In order to find out the result of your query in a particular order, based on one or more filed, MongoDB provides us with the sort operation.
Syntax: db.collection.find().sort({ field: direction });
Field: The name of the field you want to sort
Direction: If value of direction is passed to be 1, it will show result in ascending order. On the other hand, if the value is passed as -1, resultant will be in descending order.
Limiting Data
It restricts the number of documents returned by a query. MongoDB provides the limit() method to control the number of results.
Syntax: db.collection.find().limit(number);
Value of number in the above syntax is how many number of documents you want in return.
These are some of the basic operations that we must know before start working with MongoDB.
We have discussed all the fundamental of the MongoDB such as database, documents, collections, and most importantly the CRUD Operations. By clearing these basic concepts, you can enhance your database management skills and will also be able to use MongoDB for variety of applications in our MERN stack development. If you are looking forward to deepen your skills especially in MongoDB or a complete MERN stack course to cover the rest of the advance topics, ESS INSTITUTE, known as one of the best MERN stack institute in Delhi offers offline and online MERN stack course designed by the web development experts. Here, you will be provided with personalized guidance, hands on workshop, and also got a chance to implement your knowledge in solving real world problems.
Check 45 common interview questions for web development roles