Get a count of total documents with MongoDB while using limit?


You can use $facet operator for this. To understand the concept, let us create a collection with document. The query to create a collection with document is as follows −

> db.totalDocumentDemo.insertOne({"InstructorId":100,"InstructorName":"Larry","InstructorFav
ouriteSubject":["Java","MongoDB","Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76e6701e9c5dd6f1f78274")
}
> db.totalDocumentDemo.insertOne({"InstructorId":200,"InstructorName":"Sam","InstructorFav
ouriteSubject":["SQL Server","C#","Javascript"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76e69c1e9c5dd6f1f78275")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.totalDocumentDemo.find().pretty();

Output

{
   "_id" : ObjectId("5c76e6701e9c5dd6f1f78274"),
   "InstructorId" : 100,
   "InstructorName" : "Larry",
   "InstructorFavouriteSubject" : [
      "Java",
      "MongoDB",
      "Python"
   ]
}
{
   "_id" : ObjectId("5c76e69c1e9c5dd6f1f78275"),
   "InstructorId" : 200,
   "InstructorName" : "Sam",
   "InstructorFavouriteSubject" : [
      "SQL Server",
      "C#",
      "Javascript"
   ]
}

Here is the query to get a count of total documents from a collection −

> db.totalDocumentDemo.aggregate([
   ... {
      ... $facet:{
         ... Alldata:[{$match:{}}],
         ... totalDocument: [{ $count: 'totalDocument' }]
      ... }
   ... }
... ]).pretty();

The following is the output displaying the count of documents −

Output

{
   "Alldata" : [
      {
         "_id" : ObjectId("5c76e6701e9c5dd6f1f78274"),
         "InstructorId" : 100,
         "InstructorName" : "Larry",
         "InstructorFavouriteSubject" : [
            "Java",
            "MongoDB",
            "Python"
         ]
      },
      {
         "_id" : ObjectId("5c76e69c1e9c5dd6f1f78275"),
         "InstructorId" : 200,
         "InstructorName" : "Sam",
         "InstructorFavouriteSubject" : [
            "SQL Server",
            "C#",
            "Javascript"
         ]
      }
   ],
   "totalDocument" : [
      {
         "totalDocument" : 2
      }
   ]
}

Updated on: 30-Jul-2019

589 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements