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 count() method – Interview Questions
Q 1: What does count() method do?
Ans: It returns the number of documents matching query.
Q 2: What is a modern alternative of count()?
Ans: countDocuments().
Q 3: Can count() use filters?
Ans: Yes
Q 4: Does count() scan all documents?
Ans: Depends on the query and the indexes.
Q 5: Why is countDocuments preferred?
Ans: It provides accurate results.