16Jun 2023

All About MongoDB: The NoSQL Database

MongoDB: The NoSQL Database

NoSQL stands for “Not Only SQL” is an alternative to the relational database. In the relational database model, tables are used to store data. But the NoSQL has a variety of data models, like key-value pairs and graph formats. One of the most flexible ways of these models is the key-value pair. MongoDB is one popular NoSQL database that stores data in BSON. BSON is binary encoding JSON which stores data in key-value pairs.

Check this article on which will give an overview of SQL and NoSQL.

So let us have a deep look into the MongoDB NoSQL database.

How MongoDB Works?

Working with MongoDB NoSQL database is much easier than working with any relational database. There are no tables in MongoDB. All the data is stored in JSON format,i.e. key-value pairs. In JSON, we define a unique key with a value associated with it. These key-value pairs are stored in a document, which in turn is stored in a collection. A collection in MongoDB can have any number of documents and such documents can have any number of key-value pairs. As I mentioned earlier, data in the MongoDB database is stored in BSON. BSON is nothing but extended JSON. It supports more data types than JSON. We store anything like, string, integer, boolean, double, binary data, object, array, javascript code and many more. 

These documents are grouped inside a collection. A collection can be equivalent to a table in a relational SQL database. A collection always exists in a database and there is no pre-defined structure of a collection. In SQL, the database contains tables and in MongoDB, the database contains collections. 

Following is an example of a document that contains a few key-value pairs.

{
"name" : "Dustin",
"age" 19,
"city": "New York",
"country" : "USA"
}

There are four key-value pairs in the above document. Three of these keys or fields have strings as their values and one has an integer. You can notice, keys are always in double-quotes and so are strings. But an integer is never written inside double-quotes. This document should be inserted inside a collection. We use CRUD operations for this. We will discuss CRUD operations later in this article.

But first, let’s see how a collection looks like. Following is an example of a collection in MongoDB NoSQL database.

{
"name" : "Dustin",
"age" 19,
"city": "New York",
"country" : "USA"
}

{
"name" : "Lucas",
"age" 20,
"city": "Texas",
"country" : "USA"
}

{
"name" : "Mike",
"age" 18,
"city": "Chicago",
"country" : "USA"
}

Simply, a collection is a group of documents. 

MongoDB CRUD Operations

MongoDB CRUD operations

MongoDB provides CRUD operations that are used to create, insert, update and delete. Sometimes, working with data and databases is very complicated. The data we need to store or update or delete, sometimes need a variety of operations to be performed. MongoDB NoSQL database handles working with data very efficiently. The CRUD operations come with many additional options. These operations when combined with additional options provide great results. Let’s have a look on CRUD operations briefly.

  • Create

Create operation is used to create a document. A document is directly inserted into the collection by using insertOne() and insertMany() methods. These methods create a new document that we specify and then insert them into a collection. The following is the syntax on inserting a document inside a collection.

db.collection-name.insertOne(
{
key1 : value1,
key2 : value2,
}

We have to write the name of the collection in the place of the collection name. The document we want to insert is always written inside the insertOne function in a JSON format inclosed inside curly brackets. This is how we insert one documents inside a collection. If we want to insert more than one document at a time, we have to use insertMany.

db.collection-name.insertMany(
[{
key1 : value1,
key2 : value2,
},

{
key1 : value1,
key2 : value2,
},

{
key1 : value1,
key2 : value2,
}])

The above syntax defines inserting multiple documents into a collection. Instead of passing one document, we pass multiple documents in an array.

  • Read

Read operation is used to retrieve documents from a collection. MongoDB provides find() method to retrieve data. The syntax is as follows.

db.collection-name.find()

The find() method has two parameters. The first parameter is the query and the second is the projection. If no parameter is given, it will retrieve every document in a collection. 

db.collection-name.find({"key" : "value"}, {"key1" : 1, "key2" : 0})

In the second parameter, the key with value 1 will appear in the result while the key with value 0 won’t.

To view the result in a more readable format, we can use pretty() method with find()

db.collection-name.find({"key" : "value"}, {"key1" : 1, "key2" : 0}).pretty(()
  • Update

We may require to modify a document once it is inserted into a collection. The update operation is used for making changes in the existing database. MongoDB database provides two methods for update operations, updateOne() and updateMany(). The updateOne() updates a single document. It has three parameters. The first parameter is the filter(condition), the second one is the update itself while the third one consists of few options. The third parameter is optional.

To update a single document, we use the following syntax.

db.collection-name.updateOne({"key" : "value"}, { $set : { "key1" : "value"}})

In the second parameter, we use a $set operator to set the update. There is a third parameter also. It has a few options. The most important and commonly used of these options is upsert. Whenever there is no matching document in the collection, the upsret option will add a new document which we specified in the update operation. But first, we have to add upsert as the third parameter and set it to true. 

db.collection-name.updateOne({"key" : "value"},
{ $set : { "key1" : "value"}}, {upsert : true})
  • Delete

As the name suggests, Delete operation is used to delete documents from a collection. There are two method for delete operation, deleteOne() and deleteMany(). To delete a single document, we use the deleteOne() method.

db.collection-name.deleteOne({"key" : "value"})

The deleteOne() method has one parameter. This parameter specifies the filter. To delete multiple documents, we use deleteMany() method. 

db.collection-name.deleteMany({"key" : "value"})

Example of MongoDB Operations

We will discuss an example of MongoDB database CRUD operations. First, we have to create a database. Let’s create a database and name it “demoDB”.

> use demoDB
switched to db demoDB
>

create mongodb database

There is currently no collection is this database. We can verify it by using the “show collections” command.

> use demoDB
switched to db demoDB
> show collections
>

There is no result for these commands. This means there is no collection present in the demoDB database. To create a collection, we can use the following command.

> db.createCollection("demoCollection")
{ "ok" : 1 }
>

create collection mongodb

Now we have one collection in the demoDB database named demoCollection. Let’s insert a document in the new collection.

> db.demoCollection.insertOne({"name":"Dustin","age":19,"city":"New york"})
{
"acknowledged" : true,
"insertedId" : ObjectId("5d3b3d607d9aaf21ac74a3e4")
}
>

insert document in collection mongodb

Let us retrieve data from demoCollection collection using find() method.

> db.demoCollection.find().pretty()
{
"_id" : ObjectId("5d3b3d607d9aaf21ac74a3e4"),
"name" : "Dustin",
"age" : 19,
"city" : "New york"
}
>

retreive data from collection mongodb

Now this collection has one document. We can use update operations to modify this document. Let’s change the age to 29. We can use updateOne to make this change.

> db.demoCollection.updateOne({"name":"Dustin"}, {$set : {"age":29}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>

update data in mongodb

Let us verify using find() method.

> db.demoCollection.find().pretty()
{
"_id" : ObjectId("5d3b3d607d9aaf21ac74a3e4"),
"name" : "Dustin",
"age" : 29,
"city" : "New york"
}
>

find data in mongodb

Yes, age is updated. Now we can use delete operation to delete this document. We can use deleteOne() method for this.

> db.demoCollection.deleteOne({"name":"Dustin"})
{"acknowledged" : true, "deletedCount" : 1 }
> db.demoCollection.find().pretty()
>

deleta document in mongodb

We deleted the document where the name was Dustin. We can also delete the collection by using the following command.

> db.demoCollection.drop()
true
>

delete document drop command mongodb

Let us verify by using the show collections command.

> show collections
>

show collections in mongodb

Important Terms in MongoDB

Important terms in MongoDB

There are many different terms used in MongoDB NoSQL database. The following are some of the important terms used in the MongoDB database.

  • Document: A document is a record in MongoDB where data is stored in key-value pairs.
  • Collection: A collection is a group of documents.
  • Database: A database is where all the collections are present.
  • Key-value pairs: Data in MongoDB is stored in JSON format. JSON stores data in key-value pairs.
  • JSON: It is a data-interchange format we use in MongoDB to store data.
  • BSON: BSON is extended JSON which supports a variety of data types.
  • _id: _id is a field auto-generated whenever a document is created. The value of _id is unique.

Advantages and Disadvantages of MongoDB

MongoDB NoSQL database is widely used in the modern web. It is preferred over relational databases because it has many advantages.

MongoDB advantages disadvantages

Advantages of MongoDB

The following are the few advantages of MongoDB NoSQL database over relational databases.

  • MongoDB is a schema-less NoSQL database. We do not need to design the schema of the database when we are using MongoDB. This saves a lot of time. Thus, the code we write defines the schema.
  • No complex joins are needed in MongoDB. There is no relationship among data in MongoDB.
  • MongoDB is easy to scale.
  • It is very easy to set-up and install MongoDB.
  • The document query language supported by MongoDB is very simple as compared to SQL queries.
  • Because the MongoDB uses JSON format to store data, it is very easy to store arrays and objects.
  • MongoDB is free to use. There is no cost for it.
  • Performance of MongoDB is much higher than compared to any relational database.
  • There is no need for mapping of application objects to database objects in MongoDB.
  • MongoDB uses internal memory for storage which enables faster access to the data.

Disadvantages of MongoDB

There are a few disadvantages of the MongoDB NoSQL database as well.

  • MongoDB uses high memory for data storage.
  • There is a limit for document size, i.e. 16mb.
  • There is no transaction support in MongoDB.

MongoDB vs RDBMS

MongoDB NoSQL database and relational databases are different in many aspects. There are a few key differences between both, which we will discuss below.

  • In RDBMS, We need to create tables, schemas, and relations first. But in MongoDB, there is no need for such tables, schema, and relations. 
  • To join two tables, In RDBMS, we have to use joins which are a bit complex. But in MongoDB, there are no joins. We can change the structure of the document in such a way that the other document can be embedded inside the other.
  • We need to set the primary key of every table in RDBMS. MongoDB provides an _id field which is created itself with every document and it acts as the primary key.
  • Setting up a relational database is not easy while setting up MongoDB is very simple. 
  • RDBMS is not suitable for hierarchical data storage while MongoDB is best for it.
  • RDBMS is slower as compared to NoSQL databases. MongoDB is 100 times faster than RDBMS.

Conclusion

MongoDB is one of the most widely used NoSQL databases on the modern web. It is easy to understand. The document query language provides a lot of options and it is as powerful as the SQL. Unlike relational databases, MongoDB is easy to scale. MongoDB is widely used along with NodeJS frameworks and AngularJS frameworks and ReactJS. It is a core part of the MEAN and MERN stack.

Acodez is a top website design and web development company in India offering all kinds of web design and development services to its clients using the latest technologies. We are also a digital marketing agency providing SEO, SMM, SEM, Inbound marketing services, etc at affordable prices. For further information, please contact us.

Looking for a good team
for your next project?

Contact us and we'll give you a preliminary free consultation
on the web & mobile strategy that'd suit your needs best.

Contact Us Now!
Jamsheer K

Jamsheer K

Jamsheer K, is the Tech Lead at Acodez. With his rich and hands-on experience in various technologies, his writing normally comes from his research and experience in mobile & web application development niche.

Get a free quote!

Brief us your requirements & let's connect

Leave a Comment

Your email address will not be published. Required fields are marked *