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