To get the size of all the documents in a query, you need to loop through documents. Let us first create a collection with documents −
> db.sizeOfAllDocumentsDemo.insertOne({"StudentFirstName":"John","StudentSubject":["MongoDB","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c0c1edc6604c74817cd7") } > db.sizeOfAllDocumentsDemo.insertOne({"StudentFirstName":"Larry","StudentSubject":["MySQL","PHP"],"StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c0d9edc6604c74817cd8") } > db.sizeOfAllDocumentsDemo.insertOne({"StudentFirstName":"Chris","StudentSubject":["SQL Server","C#"],"StudentAge":23,"StudentCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c0fbedc6604c74817cd9") }
Following is the query to display all documents from a collection with the help of find() method −
> db.sizeOfAllDocumentsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd3c0c1edc6604c74817cd7"), "StudentFirstName" : "John", "StudentSubject" : [ "MongoDB", "Java" ] } { "_id" : ObjectId("5cd3c0d9edc6604c74817cd8"), "StudentFirstName" : "Larry", "StudentSubject" : [ "MySQL", "PHP" ], "StudentAge" : 21 } { "_id" : ObjectId("5cd3c0fbedc6604c74817cd9"), "StudentFirstName" : "Chris", "StudentSubject" : [ "SQL Server", "C#" ], "StudentAge" : 23, "StudentCountryName" : "US" }
Following is the query to get the size of all the documents in a query −
> var allDocument = db.sizeOfAllDocumentsDemo.find(); > var counter = 0; > allDocument.forEach( ... function(myDocument) { ... counter = counter+Object.bsonsize(myDocument) ... } ... ); > print(counter);
This will produce the following output −
358