MongoDB – Document Based NoSQL database

MongoDB is one of the top most popular modern databases which is now widely used for building modern-day applications. You can learn it by enrolling to a professional IT institute. It is different from traditional RDBMS and it is categorized as a NoSQL database because of the flexibility of schema which it provides. MongoDB is easy to use and the data is stored in the JSON (JavaScript Object Notation) format which stores data in key-value pairs and it is very easy for developers while they work on database related queries. So, MongoDB provides:

  • Simple to use, Flexible, Powerful, Scalable and Development Friendly are some of the key reasons behind the popularity of MongoDB.
  • It is a cross-platform database, which means it can be run on various operating systems and various computer architectures.
  • MongoDB removes the complex Object-Relation Mapping (ORM) layer and uses a flexible data model which helps in evolving the database with the business changing requirements. So, MongoDB adapts faster to the business requirements than the SQL databases.

What is a NoSQL or “Not Only SQL” database?

A NoSQL database is a kind of database that provides the mechanism of storage, retrieval and manipulations of data in a different approach in comparison to RDBMS.

MongoDB is one of the NoSQL databases which is a document-oriented database that stores data in JSON (i.e., sets of key-value or field-value pairs) like documents with the dynamic schema. The concept of dynamic schema is to store the records without worrying too much about the structural part of the database. So, one document can be different from another one in the same collection.

MongoDB database architecture is designed on collections and documents.

What is a collection in MongoDB?

A collection in MongoDB is a grouping of MongoDB documents that hold data, usually dynamic because the collection does not enforce a schema.

In RDBMS, we know that schema is enforced by the table and thus, the data in the rows should be consistent in terms of the number of columns and column type as defined in a table while creating it. But, in MongoDB, collection can hold multiple documents which can have different documents with different data in terms of key-value pairs and data types.

A sample collection of Documents in MongoDB:

sample collection of Documents in MongoDB

Here we can see how the collection binds different documents together in MongoDB.

What is a document in MongoDB?

We know that MongoDB is a document-based database and each record in MongoDB is termed as a document. These documents are made up of key-value or field-value pairs which are just like JSON. But these documents are stored in BSON (Binary JSON) format in MongoDB.

So, to do it practically, we can use MongoDB GUI applications or even MongoDB Shell.

What is a MongoDB Shell?

Connecting to MongoDB Shell:

MongoDB will be installed in the following path

C:\Program Files\MongoDB\Server\4.2\bin

get into it and then in cmd type “mongo

  • show databases

Will show the database comes by default or if u created it as well.

MongoDB Shell

  • use <database name>

This command will now let us use or create a particular database so that you can perform some actions on that database. Here, <database-name> is the name of the database you want to create. While using this command to create a database, you must create a collection and insert at least one record so that the database gets created.

Database name

  • show collections

Will show you the list of collections that exist in the current database which is in use.

show collections

  • DB.createCollection

This will create a collection inside the database

create collection

  • <collectionName>.drop

The collection name will delete that particular collection from the working database.

drop database faculty

  • dropDatabase

This command is used to delete or remove a database in MongoDB. The currently working DB is the one that will be deleted.

db.dropDatabase

  • <collectionName>.insertOne({name:”HR”,noe:10})

This method is used to insert a document (a tuple in RDBMS) in the mentioned collection. The document is represented in the form of a Key: Value pair. Key should always be unique. Once the document gets saved, Mongo will provide a unique id for the respective document.

DB.collectionName

Note: Previously I deleted the Database and the Collection and thereafter I re-created them.

  • Insert document via creating Object

Here a variable is created by the name “deptObj” that contains JSON data. We can pass a variable as an argument within insert one ()

deptObj

  • db.<collectionName>.insertMany([{}, {}])

Insert multiple documents via creating an Array of Objects

var deptArr = [

{

name: “ec”,

email: “ec@domain.com

},

{

name: “eee”,

email: “eee@domain.com”

}

];

Here we created a variable that contains a JSON array consisting of Objects. Using insertMany() method we can generate multiple documents inside MongoDB collection.

insertMany

  • The _id Field

In MongoDB, every document must have an id field and it should be unique. It acts as a primary key in the MongoDB collection. MongoDB automatically creates the id field if not specified during the creation of a new document and its value is assigned as the ObjectId type by default.

But if we want, we can also specify the _id value. One thing must be to ensure that, it should be unique in a collection; otherwise, the document will not be created.

var deptObj = {

_id: 13,

name: “ec”,

email: “ec@domain.com”

}

ObjectId

Note: Since _id was specified by us during document creation, it showed us as “insertedId”.

  • <collectionName>.find()

This method is used to read one or more documents for a specific collection.

db.dept find

Note: Here we are reading Documents without Query.

  •  <collectionName>.find({key:value})

This method can also be used to read documents from a collection that has specific keys and values. Here the key is “name” and the value is “ec”

key value

If a match is not found then no data will be returned and the prompt will be returned back.

  • <collectionName>.find().pretty()

This method is used along with the find () method to remove the readability of the results generated by the find() method. Now we will get the results in easy-to-read attractive format.

find.prettyMongoDB Update Operations:

  • Updating Single Document using update () method

$set Operator

This operator is used to update the values of one or more fields in a document in association with the selection query given in the update method.

db.<collectionName>.update( <find variable>, { $set: <replace variable>}

findquery

Note: findQuery: variable is responsible for finding the existing key: value based on which search will be taking place.

replaceQuery: variable holds the new data that will replace the existing data.

In the above picture, we saw how to update a single document, and when the operation is successful, the resultant output is, number of matches is 1 and number of modifications is also 1.

  • Updating Multiple Documents using update () method

Two variables “findQuery” and “replaceQuery” has been created. The first one has JSON data for the selected query and the second one has JSON data for updating the document. The code for the same is as follows:

var findQuery = {

email: ‘ec@domain.com’

};

var replaceQuery = {

email: ‘ec@domain.edu’

};

And then, have used the MongoDB update() method to update all the documents based on this selection Query in the MongoDB, dept Collection, with multi option set to true.

  • <collectionName>.update( <find variable>,

{ $set: <replace variable>}, {multi: true})

replace variable

In the above picture, we saw how to update multiple documents, and when the operation is successful, the resultant output is, number of the match is 2 and number of modifications is also 2. The multi-option is set to true, which will allow updating multiple documents based on search criteria but if multi is set to false then it will update a single document only.

  • Updating Single Document using updateOne() method

Two variables “findQuery” and “replaceQuery” has been created. The first one has JSON data for the selected query and the second one has JSON data for updating the document. The code for the same is as follows:

var findQuery = {

email: ‘it@domain.com’

};

var replaceQuery = {

email: ‘it@domain.edu’

};

And then, have used the MongoDB updateOne() method to update a document based on this selection Query in the MongoDB, dept Collection.

  • <collectionName>.updateOne( <find variable>, { $set: <replace variable>}};

find variable

In the above picture, we saw how to update a single document, and when the operation is successful, it returns matchedCount as 1 and modifiedCount also like 1.

  • Updating Multiple Documents using updateMany() method

Two variables “findQuery” and “replaceQuery” has been created. The first one has JSON data for the selected query and the second one has JSON data for updating the document. The code for the same is as follows:

var findQuery = {

email: ‘ec@domain.edu’

};

var replaceQuery = {

name: ‘ec new’

};

And then, have used the MongoDB updateMany() method to update multiple documents based on this selection Query in the MongoDB, dept Collection.

  • <collectionName>.updateMany( <find variable>,

{ $set: <replace variable>}, {upsert: Boolean}};

Boolean

findQuery variable is searching for key: email whose value is “ec@domain.edu” on finding it, we would like to replace key: name with a new value “ec first year”. Here upsert: Boolean has been used which mean if there is no search match found then a new document will be automatically be created by updateMany().

I hope you learnt something new from this blog. Please share it with your friends and stay tuned for more updates. If you are an IT enthusiastic, and want to gather more knowledge, you can go through some of our blogs given below.

MongoDB delete operations… COMING SOON

Swarup Kr

Swarup Kr Saha is a Senior Technical Analyst cum Corporate Trainer. He is seasoned and successful in creating fresher’s training programs for the IT aspirants and helping them excel in their careers. An enthusiast in IoT, he has more than 10 years of experience. He believes in a continuous learning procedure and is committed to providing Quality Training in the areas of ABCD (Application Development, Big Data, Cloud and Database). Using his exemplary skills, he also develops Full-Stack Web and Mobile (Android & iOS) App connecting IoT with REST-API based solutions.