- 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 the size of a collection in MongoDB using conditions?
Let us first create a collection with documents −
> dbmongoDBCollectionSizeDemoinsertOne({"Name":"John", "Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cf23e3db64a577be5a2bc16") } > dbmongoDBCollectionSizeDemoinsertOne({"Name":"Chris", "Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5cf23e45b64a577be5a2bc17") } > dbmongoDBCollectionSizeDemoinsertOne({"Name":"Robert", "Age":26}); { "acknowledged" : true, "insertedId" : ObjectId("5cf23e4db64a577be5a2bc18") }
Following is the query to display all documents from a collection with the help of find() method −
> dbmongoDBCollectionSizeDemofind();
This will produce the following document −
{ "_id" : ObjectId("5cf23e3db64a577be5a2bc16"), "Name" : "John", "Age" : 23 } { "_id" : ObjectId("5cf23e45b64a577be5a2bc17"), "Name" : "Chris", "Age" : 24 } { "_id" : ObjectId("5cf23e4db64a577be5a2bc18"), "Name" : "Robert", "Age" : 26 }
Following is the query to get the collection size using conditions −
> var collectionsize = 0; > dbmongoDBCollectionSizeDemofind({Name:'Robert'})forEach(function(d) { var s = Objectbsonsize(d); collectionsize=collectionsize +s; }) > print(collectionsize);
This will produce the following document −
52
Advertisements