MongoDB Interview Questions

I am sharing top 41 MongoDB Interview Questions, which will help you to crack the MongoDB Interview.

Q1:- What is MongoDB?

Ans:- MongoDB is a NoSql Database, it is based on BSON.

Q2:- Why is MongoDB not chosen for a 32-bit system?

Ans:- Mongo DB is not considered as a 32-bit system because for running the 32-bit MongoDB, with the server, information and indexes require 2 GB. That is why it is not used in 32-bit devices

Q3:- How to create database?

Ans:- use databaseName

Q4:- How to drop the database?

Ans:- db.dropDatabse() command is used to drop a database.

Q5:- What is a Collection in MongoDB?

Ans- In MongoDB, a collection is a group of MongoDB documents.

Q6:- How to create collection?

Ans:- db.createCollection(name,options)

Q7:- How to drop a collection?

Ans:- db.collectionName.drop()

Q8:- How to insert a document in the collection?

Ans:- db.collectionName.insertOne() is used to add single document in the collection.
db.collectionName.insertMany() is used to add multiple documents in the collection.

Q9:- What is the use of the save() method?

Ans:- The save() method is used to replace the existing document with a new document.

Q10:- Which method is used to update the document?

Ans:- If you want to update single document then use


db.collectionName.updateOne()

If you want to update Multiple documents then use


db.collectionName.updateMany()

Q11:- Which method is used to remove a document from a collection?

Ans:- The remove() method is used to remove a document from a collection.

Q12:- What is MongoDB Projection?

Ans:- Projection is used to select only the necessary data. It does not select the whole data of a document.
readmore…

Q13:- What is the use of the pretty() method?

Ans:- The pretty() method is used to show the results in a formatted way.

Q14:- What is the use of the limit() method?

Ans:- The limit() method is used to limit the records in the database.

Q15:- What is the syntax of the limit() method?

Ans:- The syntax of the limit() method is as follows


>db.COLLECTION_NAME.find().limit(NUMBER)

Q16:- What is the syntax of the sort() method?

Ans:- In MongoDB, the following syntax is used for sorting documents:


>db.COLLECTION_NAME.find().sort({KEY:1})

Note: 1 is used for ascending order.
-1 is used for descending order.

Q17:- What is the syntax of the skip() method?

Ans:- The syntax of the skip() method is as follows:


>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

Q18:- How to filter the records?

Ans:-


db.users.find({name: /a/}) //like '%a%'
db.users.find({name: /^pa/}) //like 'pa%'
db.users.find({name: /ro$/}) //like '%ro'

Q19:- Which command is used to create a backup of the database?

Ans:- The mongodump command is used to create a backup of the database.

Q20:- Which command is used to restore a backup into the database?

Ans:- The mongorestore command is used to restore into the database.

Q21:- What is the use of an Index in MongoDB?

Ans:- indexes are used to increase the performance to get the records from the database.

Q22:- How to create an index in MongoDB?

Ans:-


db.collectionname.createIndex({'documentkeyname':1})

Q23:- How to get the indexes from the collection?

Ans:-


db.collectionName.getIndexes()

Q24:- Define Namespace in MongoDB?

Ans:- MongoDB stores BSON objects in collections. The concatenation of the database name and the collection name (with a period in between) is called a “namespace”.

Q25:- What is Replication?

Ans:- MongoDB replication is distributed to the data across different machines.

Q26:- What is the use of GridFS in MongoDB?

Ans:- GridFS is used for storing and retrieving large files, such as audio, image, and video files.

Q27:- What is the use of Journaling in MongoDB?

Ans:- Journaling is used for safe backups in MongoDB.

Q28:- What is the use of Profiler?

Ans:- Profiler is used to show the performance characteristics of every operation against the database.

Q29:- What type of data is stored by MongoDB?

Ans:- MongoDB stores data in the form of documents, which are JSON-like field and value pairs.

Q30:- What is the purpose of Replication?

Ans:- Replication provides redundancy, and it increases data availability.

Q31:- What are Embedded documents?

Ans:- Embedded documents capture relationships between data by storing related data in a single document structure.

Q32:- What is Vertical Scaling?

Ans:- Vertical scaling adds more CPU and storage resources to increase capacity.

Q33:- Define Horizontal Scaling.

Ans:- Horizontal scaling divides the dataset and distributes data over multiple servers, or shards.

Q34:- What is Aggregation pipeline?

Ans:- The aggregation pipeline is a framework for performing aggregation tasks. The pipeline is used to transform documents into aggregated results.

Q35:- What is sharding?

Ans:- Sharding is a method for distributing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations.

Q36:- Which are the storage engines used by MongoDB?

Ans:- MMAPv1 and WiredTiger are two storage engines used by MongoDB.

Q37:- What is the profiler in mongodb?

Ans:- MongoDB Profiler allows you to analyze all the queries which are being run by the database system.
Note:- MongoDB would be to use the query profiler to track and diagnose slow queries.

Q38:- MongoDB store data in which format?

Ans:- MongoDB uses documents to store data into the collections.

Q39:- What is replica set in MongoDB?

Ans:- A replica can be specified as a group of mongo instances that host the same data set. In a replica set, one node is primary, and another is secondary. All data is replicated from primary to secondary nodes.

Q40:- What is primary and secondary replica set in MongoDB?

Ans:- In MongoDB, primary nodes are the node that can accept write. These are also known as master nodes. The replication in MongoDB is a single master so, only one node can accept write operations at a time.
Secondary nodes are known as slave nodes. These are read-only nodes that replicate from the primary.

Q41:- What is Ad-hoc Queries?

Ans:- Ad-hoc queries are the queries not known while structuring the database. So, MongoDB provides ad-hoc query support which makes it so special in this case.

Create Database

firstly open the terminal. If you have mongo credentials then write the below command.


mongo -u admin
Enter password:

Note:- where admin is a username

If you did not create credentials then you can directly login write the command


mongo

Now, create the database through below command
use DatabaseName


 > use employee_management
 > switched to db employee_management

if you want to see all databases then write the below command.


> show dbs

Note:- it will show all databases which has collection.

Create Collection

db.createCollection(name, options) is used to create collection in MongoDB. when you create a document then the collection is automatically created if it does not exist. The collection is like a table in RDBMS.


> db.createCollection("collectionName",options);

collectionName:- is a string type, specifies the name of the collection to be created.

options:- is a document type, specifies the memory size and indexing of the collection. It is an optional parameter.

Field
Type
Description

capped
Boolean
Optional. To create a capped collection you should specify true. If you specify true, you must also set a maximum size in the size field.

autoIndexId
Boolean
Optional. If you specify false then disable the automatic creation of an index on the _id field but now it is deprecated since version 3.2

size
number
Optional. Specify a maximum size in bytes for a capped collection. Once a capped collection reaches its maximum size, MongoDB removes the older documents to make space for the new documents.

max
number
(Optional) Specifies the maximum number of documents allowed in the capped collection.

	
> db.createCollection("employees");
Output
{ “ok” : 1 }

How to create Collection through Document?
When you create a document then it checks collection is exists or not if not exists then create automatically.

	
> db.collectionName.insert(objectValue);
> db.users.insert({
	"name":"John",
	"age":35
});

Now, check all collection in the database

	
> show collections
Output
employees

MongoDB Insert Document

To insert document in the collection through multiple methods like insert(), insertOne() and insertMany(). it works like insert row into table in RDBMS.

Syntax:-


> db.collectionName.insert(document);

In RDBMS:-


insert into tableName(field1,field2...) values('Value1','Value2'..)

Example:-


db.employees.insert({
	name:"John",
	age: 35,
	department:"department A",
	salary:100000
})

if the document is inserted then show a message

WriteResult({ “nInserted” : 1 })

insertOne() method

This method is used to insert only one document in the collection.

Syntax:-


db.collectionName.insertOne(Document);

Example:-


> db.employees.insertOne({
	name:"Rom",
	age: 30,
	department:"department A",
	salary:50000
})

after insert successfully then show message

{
“acknowledged” : true,
“insertedId” : ObjectId(“5f26e7c0deec6e20ea057832”)
}

Note:- When use insertOne() method then show insert document id, it is generated automatically and it has unique value in the collection.

insertMany() method

This method is used to add multiple documents in the collection.

Syntax:-


db.collectionName.insertMany(multipleDocuments)

Example:-


> db.employees.insertMany([{
	name:"Tony",
	age: 31,
	department:"department B",
	salary:40000
},
{
	name:"Peter",
	age: 32,
	department:"department B",
	salary:30000
},
{
	name:"Andrew",
	age: 33,
	department:"department C",
	salary:20000
}
])

After insert successfully then show messages

{
“acknowledged” : true,
“insertedIds” : [
ObjectId(“5f26e9dedeec6e20ea057833”),
ObjectId(“5f26e9dedeec6e20ea057834”),
ObjectId(“5f26e9dedeec6e20ea057835”)
]
}

MongoDB Update Document

To update the documents in the collection through multiple methods like update(), updateOne(), updateMany() . it works like update row into table in RDBMS.

Syntax:-


> db.collectionName.update({whereCondition},{newData});

In RDBMS:-


update tableName set field1='Value1',field2='Value2' where conditions

Example:- Suppose, You have employees collection


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"salary" : 100000
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"salary" : 50000
	}
]

Now, you want to update employee salary where name is John.


> db.employees.update({name:"John"},{$set:{salary:200000}})

if the document is updated then show a message

WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })

updateOne() method

this method is used to update only one document in the collection.

Syntax:-


> db.collectionName.updateOne({whereCondition},{newData});

Example:-


> db.employees.updateOne({name:"Rom"},{$set:{salary:70000}})

after update successfully then show message

{ “acknowledged” : true, “matchedCount” : 1, “modifiedCount” : 1 }

updateMany() method

This method is used to update multiple documents in the collection.

Syntax:-


> db.collectionName.updateMany({whereCondition},{newData})

save() method

This method is used to replace exists documents with the new document.

Syntax:-


> db.collectionName.save({whereCondition},{newData})

MongoDB Delete Document

There are multiple methods in MongoDB to delete the documents from the collections like remove(), deleteOne(), deleteMany() methods. it works like a delete a row from the table in RDBMS.

Syntax:-


> db.collectionName.remove({whereCondition},justOne);

justOne:- (Optional) if set to true or 1, then remove only one document.

In RDBMS:-


delete from tableName where condition=someValue

Example:-
Suppose, you have employees collection


[
	{
	"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
	"name" : "John",
	"age" : 35,
        "department":"department A"
	},
	{
	"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
	"name" : "Rom",
	"age" : 31,
        "department":"department A"
	},
	{
	"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
	"name" : "Mathew",
	"age" : 32,
        "department":"department A"
	}
]

Now, you want to delete document where name is Rom


db.employees.remove({name:"Rom"},1)

if the document is deleted then show a message.

WriteResult({ “nRemoved” : 1 })

deleteOne() method

this method is used to delete one document from the collection.

Syntax:-


db.collectionName.deleteOne({whereCondition})

Example:-


db.employees.deleteOne({name:"John"});

Output:-

{ “acknowledged” : true, “deletedCount” : 1 }

deleteMany() method

this method is used to delete multiple documents from the collection.

Syntax:-


db.collectionName.deleteMany({whereCondition})

Example:-


db.employees.deleteMany({department:"department A"});

Output:-

{ “acknowledged” : true, “deletedCount” : 3 }

remove({}) method

this method is used to delete all documents from the collection.

Syntax:-


db.collectionName.remove({});

after delete successfully then show message

WriteResult({ “nRemoved” : NumberOfDocumentsDeleted })

Example:-


db.employees.remove({})

MongoDB Projection

MongoDB projection is used to get the necessary data of the documents from the collection.

find() method

this method is used to get the documents from the collection.

Syntax:-


db.collectionName.find();

Example:- Suppose you want to get all records from the employees collection.


db.employees.find();

It will show all documents data and results will be in object format.

Output:-
{ “_id” : ObjectId(“5f26e736deec6e20ea057831”), “name” : “John”, “age” : 35, “department” : “department A”, “salary” : 200000 }
{ “_id” : ObjectId(“5f26e7c0deec6e20ea057832”), “name” : “Rom”, “age” : 30, “department” : “department A”, “salary” : 70000 }
{ “_id” : ObjectId(“5f26e9dedeec6e20ea057833”), “name” : “Tony”, “age” : 31, “department” : “department B”, “salary” : 40000 }
{ “_id” : ObjectId(“5f26e9dedeec6e20ea057834”), “name” : “Peter”, “age” : 32, “department” : “department B”, “salary” : 30000 }
{ “_id” : ObjectId(“5f26e9dedeec6e20ea057835”), “name” : “Andrew”, “age” : 33, “department” : “department C”, “salary” : 20000 }

find() method with where condition

first parameter in find() method is used for where condition.

Syntax:-


db.collectionName.find({where_condition});

Example:-
Suppose, you want to get record where department is department C


db.employees.find({department:"department C"});
Output
{ “_id” : ObjectId(“5f26e9dedeec6e20ea057835”), “name” : “Andrew”, “age” : 33, “department” : “department C”, “salary” : 20000 }

get the specific data through {key_name:1} from the collection

If you want to find specific data from the document then use two parameters where first parameter is used for where condition while second parameter is used to get specific data from the collection through {key_name:1}.
Syntax:-


db.collectionName.find({whereCondition},{key_name:1});

Example:-


db.employees.find({},{name:1});

Output:-

{ “_id” : ObjectId(“5f26e736deec6e20ea057831”), “name” : “John” }
{ “_id” : ObjectId(“5f26e7c0deec6e20ea057832”), “name” : “Rom” }
{ “_id” : ObjectId(“5f26e9dedeec6e20ea057833”), “name” : “Tony” }
{ “_id” : ObjectId(“5f26e9dedeec6e20ea057834”), “name” : “Peter” }
{ “_id” : ObjectId(“5f26e9dedeec6e20ea057835”), “name” : “Andrew” }

Note:- _id value will show automatically.

If you do not want _id value

_id will always display when you get the data if you do not want this then use _id:0


db.employees.find({},{_id:0,name:1});

Output:-

{ “name” : “John” }
{ “name” : “Rom” }
{ “name” : “Tony” }
{ “name” : “Peter” }
{ “name” : “Andrew” }

findOne() method

this method is used to get the only one record from the document.

Example:-


db.employees.findOne({},{name:1});

Output:-

{ “_id” : ObjectId(“5f26e736deec6e20ea057831”), “name” : “John” }

find().toArray() method

this method is used to get the result into Array format.


db.employees.find().toArray();

Output:-

[
{
“_id” : ObjectId(“5f26e736deec6e20ea057831”),
“name” : “John”,
“age” : 35,
“department” : “department A”,
“salary” : 200000
},
{
“_id” : ObjectId(“5f26e7c0deec6e20ea057832”),
“name” : “Rom”,
“age” : 30,
“department” : “department A”,
“salary” : 70000
},
{
“_id” : ObjectId(“5f26e9dedeec6e20ea057833”),
“name” : “Tony”,
“age” : 31,
“department” : “department B”,
“salary” : 40000
},
{
“_id” : ObjectId(“5f26e9dedeec6e20ea057834”),
“name” : “Peter”,
“age” : 32,
“department” : “department B”,
“salary” : 30000
},
{
“_id” : ObjectId(“5f26e9dedeec6e20ea057835”),
“name” : “Andrew”,
“age” : 33,
“department” : “department C”,
“salary” : 20000
}
]

MongoDB limit() method

In MongoDB, limit() method is used to get the limit of documents from the collection. this method has only one parameter which should be numeric only.

Syntax:-


 db.collectionName.find().limit(number);

Suppose, you have employees collection which has 3 documents.

[
{
“_id” : ObjectId(“5f26e736deec6e20ea057831”),
“name” : “John”,
“age” : 35,
“department” : “department A”,
“salary” : 200000
},
{
“_id” : ObjectId(“5f26e7c0deec6e20ea057832”),
“name” : “Rom”,
“age” : 30,
“department” : “department A”,
“salary” : 70000
},
{
“_id” : ObjectId(“5f26e9dedeec6e20ea057833”),
“name” : “Tony”,
“age” : 31,
“department” : “department B”,
“salary” : 40000
}
]

Now, if you want to get only one documents then you have to use the limit() method.


> db.employees.find().limit(1).toArray();

Output:-

[
{
“_id” : ObjectId(“5f26e736deec6e20ea057831”),
“name” : “John”,
“age” : 35,
“department” : “department A”,
“salary” : 200000
}
]

MongoDB sort() method

In MongoDB, sort() method is used to get the documents in ascending or descending order corresponding to the document key.

Ascending Order

to get the documents in the ascending order through sort({key_name:1}) method

Syntax:-


 db.collectionName.find().sort({key_name:1});

Suppose, you have employees collection


[
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	{
		"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
		"name" : "Rom",
		"age" : 30,
		"department" : "department A",
		"salary" : 70000
	},	
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	}
]

Now, you want to get the documents in ascending Order corresponding to name wise.


> db.employees.find().sort({name:1}).toArray();

Output:-


[
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	},
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	
	{
		"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
		"name" : "Rom",
		"age" : 30,
		"department" : "department A",
		"salary" : 70000
	}
]

Descending Order

to get the documents in the descending order through sort({key_name:-1}) method
Syntax:-


 db.collectionName.find().sort({key_name:-1});

Suppose, you want the get the documents from the employees collection in descending order corresponding to name wise.


> db.employees.find().sort({name:-1}).toArray();

Output:-


[
	
	{
		"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
		"name" : "Rom",
		"age" : 30,
		"department" : "department A",
		"salary" : 70000
	},
	
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	}
]


MongoDB skip() method

In MongoDB, skip() method is used to skip the documents from the collection.
We can use the skip method to implement pagination logic.
Syntax:-


 db.collectionName.find().skip(numberOfDocument);

Suppose, you have employees collection and it has 5 documents


[
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	{
		"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
		"name" : "Rom",
		"age" : 30,
		"department" : "department A",
		"salary" : 70000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057833"),
		"name" : "Tony",
		"age" : 31,
		"department" : "department B",
		"salary" : 40000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057834"),
		"name" : "Peter",
		"age" : 32,
		"department" : "department B",
		"salary" : 30000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	}
]

Now, you want to get the documents which are starting from the 3rd document.


> db.employees.find().skip(2).toArray();

Output:-


[
	
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057833"),
		"name" : "Tony",
		"age" : 31,
		"department" : "department B",
		"salary" : 40000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057834"),
		"name" : "Peter",
		"age" : 32,
		"department" : "department B",
		"salary" : 30000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	}
]

MongoDb join

In SQL Database, there are many ways to create the join between two or more tables like
Left Join
Right Join
Inner Join
Full Join
Self Join

But MongoDB is a NoSQL Database so It has one method to join between two or more collection through lookup().

Syntax:-


db.collectionName.aggregate([
    { $lookup:
       {
         from: 'otherCollection',
         localField: 'collection_fieldname',
         foreignField: 'otherCollection_fieldname',
         as: 'collectionDetails'
       }
     }
    ]).toArray();

Suppose, You have two collections First is employees collection which has 3 documents and every document has 5 key fields like _id, name, age, department and salary.


[
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057833"),
		"name" : "Tony",
		"age" : 31,
		"department" : "department B",
		"salary" : 40000
	},
	
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	}
]

2) Second collection is department. which has 4 key fields like _id, name, floor and facility.


[
	{
		"_id" : ObjectId("5f27bfaddeec6e20ea057836"),
		"name" : "department A",
		"floor" : 5,
		"facility" : "standard"
	},
	{
		"_id" : ObjectId("5f27bfaddeec6e20ea057837"),
		"name" : "department B",
		"floor" : 4,
		"facility" : "good"
	},
	{
		"_id" : ObjectId("5f27bfaddeec6e20ea057838"),
		"name" : "department C",
		"floor" : 3,
		"facility" : "normal"
	}
]

Now you want to get the employees collection document with department details


db.employees.aggregate([
    { $lookup:
       {
         from: 'department',
         localField: 'department',
         foreignField: 'name',
         as: 'departmentDetails'
       }
     }
    ]).toArray();

Output:-

[
{
“_id” : ObjectId(“5f26e736deec6e20ea057831”),
“name” : “John”,
“age” : 35,
“department” : “department A”,
“salary” : 200000,
“departmentDetails” : [
{
“_id” : ObjectId(“5f27bfaddeec6e20ea057836”),
“name” : “department A”,
“floor” : 5,
“facility” : “standard”
}
]
},

{
“_id” : ObjectId(“5f26e9dedeec6e20ea057833”),
“name” : “Tony”,
“age” : 31,
“department” : “department B”,
“salary” : 40000,
“departmentDetails” : [
{
“_id” : ObjectId(“5f27bfaddeec6e20ea057837”),
“name” : “department B”,
“floor” : 4,
“facility” : “good”
}
]
},

{
“_id” : ObjectId(“5f26e9dedeec6e20ea057835”),
“name” : “Andrew”,
“age” : 33,
“department” : “department C”,
“salary” : 20000,
“departmentDetails” : [
{
“_id” : ObjectId(“5f27bfaddeec6e20ea057838”),
“name” : “department C”,
“floor” : 3,
“facility” : “normal”
}
]
}
]

MongoDB count() method

MongoDB count() method is used to get the number of documents in the collection.

Syntax:-


db.collectionName.find().count();

Suppose, you have employees collection and which has 5 documents


[
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	{
		"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
		"name" : "Rom",
		"age" : 30,
		"department" : "department A",
		"salary" : 70000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057833"),
		"name" : "Tony",
		"age" : 31,
		"department" : "department B",
		"salary" : 40000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057834"),
		"name" : "Peter",
		"age" : 32,
		"department" : "department B",
		"salary" : 30000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	}
]

Now get the number of documents in the employee’s collection.


db.employees.find().count();
Output
5

Where condition with count() method

Syntax:-


db.employees.find({where_condition}).count();

Suppose, you want to get the number of employees which has department B


db.employees.find({department:"department B"}).count();
Output
2

MongoDb Aggregation

Aggregation has the most important role in MongoDB. MongoDB Aggregation operations process data records and return computed results. Aggregation operations group values from multiple documents together and can perform a variety of operations on the grouped data to return a single result.

to perform the aggregate function in MongoDB, aggregate() is the function to be used. Following is the syntax for aggregation :


db.collection_name.aggregate(aggregate_operation)

Suppose, You have Employees collection which has multiple documents.


[
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	{
		"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
		"name" : "Rom",
		"age" : 30,
		"department" : "department A",
		"salary" : 70000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057833"),
		"name" : "Tony",
		"age" : 31,
		"department" : "department B",
		"salary" : 40000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057834"),
		"name" : "Peter",
		"age" : 32,
		"department" : "department B",
		"salary" : 30000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	}
]

Now We want to get the total of employees corresponding to department wise.


 db.employees.aggregate([{$group : {_id : "$department", total_employee : {$sum : 1}}}])

Output:-

{ “_id” : “department C”, “total_employee” : 1 }
{ “_id” : “department B”, “total_employee” : 2 }
{ “_id” : “department A”, “total_employee” : 2 }

Different Expression which is used by an aggregate function

Expression
Description
$sum
Sums up the defined value from all documents in the collection.
$min
Gets the minimum of the corresponding values from all documents in the collection.
$max
Gets the maximum of the corresponding values from all documents in the collection.
$avg
Calculates the average of all given values from all documents in the collection.
$push
Inserts the value to an array in the resulting document.
$pop
remove the value from an array in the resulting document.
$addToSet
Inserts the value to an array in the resulting document but does not create duplicates.
$first
Gets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.
$last
Gets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.

MongoDb Create User

MongoDB provides role-based access control. A user is granted one or more roles that determine the user’s access or privileges to MongoDB resources and the actions that a user can perform.

Syntax:-


> db.createUser(
{	
user: "userName",
pwd: "userPassword",
roles:[{role: "roleName" , db:"DBName"}
]
})

Note:- roles are read and readWrite

read:- User can access only for read the data from the database.

readWrite:- User can access for read and modify the database.

Example:- If user can access only read the database.


> db.createUser(
{	
user: "userName",
pwd: "userPassword",
roles:[{role: "read" , db:"DBName"}
]
})

Example:- If user can access read and modify the database.


> db.createUser(
{	
user: "userName",
pwd: "userPassword",
roles:[{role: "readWrite" , db:"DBName"}
]
})

Note:- A user can have different role for differnt database like


> db.createUser(
{	
user: "userName",
pwd: "userPassword",
roles:[{role: "readWrite" , db:"DBName1"},
       {role: "read" , db:"DBName2"}
]
})

Drop Collection

to remove the collection from the database through db.collectionName.drop() method.
Syntax:-


db.collectionName.drop()

Note:- if the collection exists then show message true if the collection does not exist then show message false;

Suppose, You have two collections department and employees. Now, check the collections in MongoDB


show collections

Output:-

department
employees

Example:-


db.employees.drop()

Output:-

true

Now get the collection


show collection

Output:-

department

How to install MongoDB

There are different ways to install MongoDB on the different operating systems but I am showing only for ubuntu and Window. There are two ways of installing MongoDB on Ubuntu systems.

MongoDB install in Ubuntu

1) Install MongoDB from apt repository

2) Install MongoDB from a downloaded.deb package

but I am representing through command base

Step 1:- Import MongoDB public GPG Key:

Before you can install any package from MongoDB apt repository, you need to download and import GPG key to your system.


wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -

Step 2:- Add MongoDB 4 APT Repository on Ubuntu 18.04 / Ubuntu 16.04

Ubuntu 18.04:


echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list

Ubuntu 16.04:


echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list

Step 3:- Install MongoDB 4 on Ubuntu 18.04 / Ubuntu 16.04


sudo apt update
sudo apt install -y mongodb-org

The service name is mongod now you can start the application by below command:


sudo systemctl enable --now mongod

Check Mongo status


sudo systemctl status mongod

Note:- If it is showing active (running) means MongoDB is running perfectly.

MongoDB install in Window

Step1:-Firstly click on the URL https://www.mongodb.com/try/download/community after that select the version and select the Platform as a Window and select the package as msi after that click on download button.

Step2:- Now, double click on the msi file which is installed after that click on the next button.

Step3:- Now, click the next button.

Step4:- Now, You can change the path, where you want to install otherwise it will be install on C drive and after that click the next button.

Step5:- Now, click the next button.

Step6:- Now, click the install button.

Step7:- Now, MongoDB is started to installing.

Step8:- Now, MongoDB is installing is going on.

Step9:- Now, MongoDB Compass is loading.

Step8:- Now, MongoDB is installed and click on the finish button.

What is MongoDB

MongoDB is a NoSQL Database. It is an open-source document-oriented database written in C++. it is used for a high volume of data storage. It is not a relational database. It has important features like indexing, regular expression, sharding data, etc.

Key Features:

1. Document-Oriented: Data is stored in collections of documents (similar to rows in a table), which can have various fields and structures.

2 Flexible Schema: MongoDB allows documents to have different structures, meaning fields can be added or removed dynamically.

3. Scalability: MongoDB is designed for horizontal scalability, meaning you can distribute your data across multiple servers easily.

4. High Performance: It’s optimized for high write and read throughput, making it suitable for real-time applications.

5. Indexing and Aggregation: MongoDB supports indexing, allowing for fast querying, and has powerful aggregation features for data processing.

6. Replication and Sharding: It provides features like replication for high availability and sharding for distributing data across multiple machines.

Advantages:-

Schemaless

Scalability

Performance

High Availability

etc.

Note:- Datastore in the MongoDB as a key-value format.

Example:-

employees collection


{
	name:"John",
	age:35,
	department:"Department A"

}

Mongo DB works based on collection and Document

Collection:- Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table but it has not enforced the same structure of the document so it is possible documents have different structures in the collection.

Document:- it is based on key-value pairs and document the same as a row in RDBMS. Documents have a dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structures.

Example:- employees collection
One Document has this structure


{
	name:"John",
	age:35,
	department:"Department A"

}

The second Document has a different structure


{
	name:"John",
	age:35,
	skill:["NodeJS","Angular","MongoDB","MySQL"],
	department:"Department A",


}

compare RDBMS and Mongo DB structure

RDBMS

MongoDB

Table

Collection

Row

Document

Column

Key

Drop Database

db.dropDatabase() method is used to drop the database.

Note:- When you drop the database then all collections and documents will be deleted off from this database.

Syntax:-


use databaseName
> db.dropDatabase()

Example:- Firstly check all database


show dbs

Output:-

employee_management
school_management

Now delete the database


use employee_management
> db.dropDatabase()

Now check the database


show dbs

Output:-

school_management

MongoDb Indexing

Indexing is the most important part of every database. It is basically used to fast retrieve data from the database.

Why indexing is most important?

Indexing is mainly used to filter data in a fast manner from the database that is the reason it is most important.

Example:- Suppose you have a collection of thousands of documents and you want to filter the document based on any condition, if you have not created indexing on the field(key) then it will check the condition in every document, so it will be impacted in the performance of the query. If we create indexing then MongoDB would use these indexes to limit the number of documents to search in the collection.

Note:- in MongoDB, every document has _id (ObjectID), which is automatically created when you create a Document and it has a 12 digit number with unique value.

divide the 12 digit Object ID

4-byte value representing the seconds since the Unix epoch (which will not run out of seconds until the year 2106)
3-byte machine identifier (usually derived from the MAC address),
2-byte process id.
3-byte counter, starting with a random value.

How to create an index?

In MongoDB, Creating a index through createIndex() method

Syntax:-


 db.collectionName.createIndex({key:1})

Where a key is a document key.

Note:- You can create multiple indexing in a document.

Example:-


 db.employees.createIndex({department:1})

Output:-

{
“createdCollectionAutomatically” : false,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1
}

Note:- Ok represent 1, it means index created successfully.

How to check the all indexes from the collection?


db.collectionName.getIndexes()

Example:-


db.employees.getIndexes()

Output:-

[
{
“v” : 2,
“key” : {
“_id” : 1
},
“name” : “_id_”,
“ns” : “employee_management.employees”
},
{
“v” : 2,
“key” : {
“department” : 1
},
“name” : “department_1”,
“ns” : “employee_management.employees”
}
]

How to drop the indexes from the collection?


db.collectionName.dropIndex({key:1})

Example:-


db.employees.dropIndex({department:1})

Output:-

{ “nIndexesWas” : 2, “ok” : 1 }