MongoDB - The Inside - Brain Mentors Skip to content

MongoDB – The Inside

Mainly ,There are two kind of databases which are largely used for application development


Now first start with the difference between these.

RDBMS v/s NO SQLDataBase

Here, We built tablesHere, we built Collection
In tables, we have rowsIn Collection , we have document
Here, we have primary KeyHere, we have _id
here, we have joinshere, we have documents
Relational Data ModelDocument Data Model

Queries Comparison

What is MongoDB?

It is a DataBase.
Mongo Means Humongous (It can store lots of Data)
MongoDB is NOSQL Based DB , it is Schema Less and it has Less Or No Relationships.
It contains Collections. Inside Collections we have Documents. It is good for Heavy Data , Extensive Read/Write DB Operations.

MongoDB – The Little History

MongoDB was founded in 2007 by Dwight Merriman , Eliot Horowitz and Kevin Ryan – the team behind DoubleClick.

At the Internet advertising company DoubleClick (now owned by Google), the team developed and used many custom data stores to work around the shortcomings of existing databases. The business served 400,000 ads per second, but often struggled with both scalability and agility. Frustrated, the team was inspired to create a database that tackled the challenges it faced at DoubleClick.

MongoDB is the leading modern, general purpose database platform, designed to unleash the power of software and data for developers and the applications they build. Headquartered in New York, with offices across North America, Europe, and Asia-Pacific, we are close to where you do business. MongoDB has more than 17,000 customers in more than 100 countries. The MongoDB database platform has been downloaded over 90 million times and there have been more than 1 million MongoDB University registrations.
Now, we will study about collections and documents

MongoDB Structure

Data Base contains Collections ,Collection contains Documents

Note: A Collection of group of
documents . Document contain JSON.
Collection has dynamic schemas.
This means that the documents within a single collection can have any number of different shapes.

MongoDB Store Data in form of BSON.

Note : Maximum Size of Document in MongoDB is 16 MB Per Document.
Document contains JSON (As a Record) , so Record Size is 16MB, and JSON internal Representation is BSON (Also It is of 16 MB).

Mongo DB EcoSystem

Enterprise Edition , Community Edition ,and Mobile Edition of Mongo DB Store Data in Mobile

Compass is a GUI Editor.
BI Connectors for Analystics for Data Science Area.
MongoDB Charts – Data Visualisation also used for Data Science Area.
Stitch- Act as a Backend as a service, Same like firebase.
MongoDB Stitch is a Backend as a Service (BaaS) that allows you to easily configure authentication, data access rules, and services. … Using Stitch to handle your backend infrastructure allows you to focus on building out the more complex nuances of your application.

How to Setup MongoDB

First of all, goto mongodb website as show here. , , then download mogodb using download button

MONGODB Server Start and Shutdown Commands

Start Mongo Local Server
mongod —dbpath=“” —port —logpath=“” —smallfiles

Running Mongo Client Shell

Shutting Down the server
use admin // switch the database

Data Types in MONGODB

Documents in MongoDB can be thought of as JSON like , in that they are conceptually same as JavaScript Object.

It has six basic data types.

  • null
  • boolean
  • numeric
  • string
  • array
  • object.

_id and ObjectId

Every document stored in MongoDB must have an _id key. It act like a primary key.
_id contain ObjectId
The ObjectId is the default type for _id. The ObjectId class is designed to be lightweight, while still being easy to generate in a globally unique way across different machines.

MongoDB distributed nature is the main reason why it uses ObjectIds are opposed to something more traditional, like an autoincrement primary key

ObjectId use 12 bytes of storage , which gives them a string representation that is 24 hexadecimal digit : 2 digit for each byte
the first four bytes for timestamp
5 to 7 bytes for machine info
8 to 9 Bytes for PID (Process ID)
10 to 12 bytes for Increment (Auto )


show dbs : This command is used to show the database

use <dbname> // this will not create Database but once we create collection and store some data, then database will be created.

db..drop() //This command is used to drop the database

db.createCollection(“ CollectionName”);//example : db.createCollection(movies);

Types of Insert methods to insert document in Collection

db.movies.insertOne({name: ʼExtractionʼ}); // This method is used to insert exactly only one document in the collection named movies

db.movies.insertMany([{id: 1001,name:ʼExtractionʼ},{id:1002, name:ʼAvengers EndGameʼ}]) //This is used to insert the array of documents in the collection named movies

db.collectionName.insert(single/ multiple); //This is used to insert either one or more documents in the collections, in other words it can be called as combination of insertOne and insertMany.

show collections //This is used to show all the collections located in our specified database

db.ColectionName.count() // This gives the total number of Collections created inside our database

Embedded Document or Nested Document

db..insertOne({id: 1001,name:ʼBRAIN MENTORSʼ,address: {city:ʼDelhiʼ,country:ʼIndiaʼ}});
//This is how nesting is done in the document,first in one document we store id,name, then we create an inside document for address. Thisis what nesting is to be called.

Find in Detail

for example : db.movies.find({name : “Extraction”})
This will Gives us the details from the database where name = ‘Extraction’


The Cursor is a MongoDB Collection of the document which is returned upon the find method execution.

By default, it is automatically executed as a loop. However, we can explicitly get specific index document from being returned cursor. It is just like a pointer which is pointing upon a specific index value.

In simple words when we call a find method, all the documents which are returned are saved in a virtual cursor. If a find method returns for a document then it is mean that the cursor has 0 – 3 index.

Inside the Cursor Object It has the Array of Objects.
db.<CollectionName>.find() .toArray()


var cursor = db.users.find();

db.<CollectionName>.find().forEach(doc=>printjson(doc)) //printjson is in but method, to print the json.

db.<CollectionName>.find({name:ʼBRAIN MENTORSʼ}).pretty() db..find({id: {$gt:1000}}

db.<CollectionName>.find({id: {$lt:1000}}

db.<CollectionName>.find({id: {$gte:1000}}

db.<CollectionName>.find({id: {$lte:1000}}

db.<CollectionName>.find({id: {$ne:1000}}


Date Comparison

var startDate = new Date(“01/01/2020”);
//. Here Our starting date is 01/01/2020
//This will return the date which is less than the start date

Using In

db.<CollectionName>.find({“salary”:{“$in”: [10222,2066,33330]}}
This will return salary from collection where salary lies in this array [10222,2066,33330]

Using NIN (Not in )

db.<CollectionName>.find({“salary”:{“$nin”: [10222,2066,33330]}}
This will return salary from collection where salary doesn’t lies in this array [10222,2066,33330]

Using Or

db.<CollectionName>.find($or: [{“salary”:4342},{id:1111}])
The $or operator performs a logical OR operation on an array of two or more and selects the documents that satisfy at least one of the <expressions> .
SO we will get the data where either salary = 4342 or id = 1111

Using And

db.<CollectionName>.find($and :[{“salary”:4342},{id:1111}])
The $and operator performs a logical and operation on an array of two or more and selects the documents that satisfy at least both of the <expressions> .
SO we will get the data where salary must be 4342 and id must be 1111

Using size


Embedded Find

Here, we are finding where city in address = Delhi. This is how we find in Nested/Embedded Document


db.<CollectionName>.find({}, {name:1})
-Name of a field value 1 means including the data to return
-By Default _id is always included in Projection
-By Using the Below Way you can exclude the _id from the Projection

Searching in Array

This is our Array ,
{name:ʼBRAIN MENTORSʼ,cities: [‘Delhiʼ,ʼMumbaiʼ]}
now , db.<CollectionName>.findOne({name:ʼBRAIN MENTORSʼ}).cities
This will give cities from array where name is BRAIN MENTORS
Here, To display the results in a formatted way, you can use pretty() method.

Searching in Embedded Document or Nested Document

First of all , we will insert document in our Collection,
db.<CollectionName>.insertOne({id: 1001,name:ʼBRAIN MENTORSʼ,address: {city:ʼDelhiʼ,country:ʼIndiaʼ}});
Here, we are searching where city in address = Delhi.
This is how we search in Nested/Embedded Document

Note : In case of Nested it mandatory to specify the nested field with parent name in quotes.

deleteOne is used to perform ddeletion only in one document,so name =’Amit’ will be deleted from one document

db.<CollectionName>.deleteMany({}) or db.<CollectionName>.remove({})
deleteMany is used to perform deletion on more than one documents

Here, this means , set Salary = 10000 where empno = 101.
UpdateOne is used to update only one document

db.<CollectionName>.updateMany({}, {$set:{salary:10000}})
The updateMany() method updates all the documents that matches the given filter. so, this will set salary = 10000 in all the documents

db.<CollectionName>.updateMany({}, {$set:{salary:10000}}, true);
// Here true refer to upserts. A upsert is a special type of update , If no document is found that matches the update criteria , a new document is created.

db.<CollectionName>.update({empno: 1001},{$inc:{salary:1000}});
Here,using this Query , for empno – 1001 , we are incrementing the salary by 1000.

db.<CollectionName>.update({empno: {$ne:1001}},{$push:{address:ʼDelhiʼ}})

db.<CollectionName>.updateMany({$ or:[{id:1001},{name:ʼAMITʼ}]},{$set: {salary:10000}})
The updateMany() method updates all the documents that matches the given filter. so, this will set salary = 10000 where id is 1001 or name is AMIT

Relations in MongoDB

To maintain relation, there are two ways :

Embedded Documents or Nested Documents – If the Data is large more than 16 MB in case of Nested Document, So go for the References.


One to One relation


db.address.insertOne({_id:ʼadd-1ʼ,city:ʼ Delhiʼ});
db.address.insertOne({city:ʼDelhiʼ,pers onref:ObjectId(‘ʼ)});


That’s All Folks For Now…..

Sign Up and Start Learning