Difference between count() and find().count() in MongoDB?

MongoDBDatabaseBig Data Analytics

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
raja
Published on 28-Mar-2019 17:51:03
Advertisements