![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between count() and find().count() in MongoDB?
There is no difference between count() and find().count(). Let us see how both of them works. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.countDemo.insertOne({"UserId":1,"UserName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f9d278d10a061296a3c5d") } > db.countDemo.insertOne({"UserId":2,"UserName":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f9d308d10a061296a3c5e") } > db.countDemo.insertOne({"UserId":3,"UserName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f9d3a8d10a061296a3c5f") } > db.countDemo.insertOne({"UserId":4,"UserName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f9d428d10a061296a3c60") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.countDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c7f9d278d10a061296a3c5d"), "UserId" : 1, "UserName" : "John" } { "_id" : ObjectId("5c7f9d308d10a061296a3c5e"), "UserId" : 2, "UserName" : "Carol" } { "_id" : ObjectId("5c7f9d3a8d10a061296a3c5f"), "UserId" : 3, "UserName" : "Bob" } { "_id" : ObjectId("5c7f9d428d10a061296a3c60"), "UserId" : 4, "UserName" : "Mike" }
Here is the query for count() that counts the number of records −
> db.countDemo.count();
The following is the output −
4
Here is the query for find().count(). The query is as follows −
> db.countDemo.find().count();
The following is the output −
4
Advertisements