Contents of page >
- 2.1) W e will use count() method to find count of all employee in collection in MongoDB.
- 2.2) Sql query equivalent to above MongoDB query is >
- 3.1) We will use find() and count() methods.
- 3.2) We can also use $count() operator to find count of all employee where salary >= 2000 in collection in MongoDB.
- 3.3) Sql query equivalent to above MongoDB query is >
count() method in Mongodb>
count() method to find count of documents in collection in MongoDB.
1) First let's create insert documents in collection in MongoDB
1.1) First, Let's create new collection and insert document >
db.employee.insert({_id : 1, firstName:"ank", salary : 1000 })
db.employee.insert({_id : 2, firstName:"ank", salary : 2000 })
db.employee.insert({_id : 3, firstName:"sag", salary : 3000 })
db.employee.insert({_id : 4, firstName:"sag", salary : 4000 })
db.employee.insert({_id : 5, firstName:"neh", salary : 5000 })
|
Above will create collection (or table) (if collection already exists it will insert documents in it).
1.2) FIND > Query all documents of collection using find() method>
db.employee.find()
|
Output>
{ "_id" : 1, "firstName" : "ank", "salary" : 1000 }
{ "_id" : 2, "firstName" : "ank", "salary" : 2000 }
{ "_id" : 3, "firstName" : "sag", "salary" : 3000 }
{ "_id" : 4, "firstName" : "sag", "salary" : 4000 }
{ "_id" : 5, "firstName" : "neh", "salary" : 5000 }
|
2) Find count of all employee in collection in MongoDB >
2.1) We will use count() method to find count of all employee in collection in MongoDB.
db.employee.count()
|
Output >
5
|
2.2) Sql query equivalent to above MongoDB query is >
select count(*) from employee;
|
3) Find count of all employee where salary >= 2000 in collection in MongoDB >
3.1) We will use find() and count() methods.
db.employee.find( { salary : {$gte : 2000} } ).count()
|
Output >
4
|
3.2) We can also use $count() operator to find count of all employee where salary >= 2000 in collection in MongoDB.
Note : $count can be used in MongoDB 3.4 or above.
db.employee.aggregate(
[ { $match: { salary : { $gte: 2000 } } }, { $count: "firstName" } ] ) |
Output >
5
|
3.3) Sql query equivalent to above MongoDB query is >
select count(*) from employee where salary >= 2000
|
4) Summary -
So in this MongoDB tutorial we learned how to use count() Method - How to find count of all employee in collection in MongoDB
count of all employee in collection in MongoDB.
db.employee.count()
|
Find count of all employee where salary >= 2000 in collection in MongoDB >
db.employee.find( { salary : {$gte : 2000} } ).count()
|
Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.
RELATED LINKS>