- Trending Categories
- 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
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 } ] }
Advertisements