Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get the size of all the documents in a MongoDB query?
To get the size of all the documents in a MongoDB query, you need to loop through the documents and calculate their cumulative BSON size using Object.bsonsize() method.
Syntax
var cursor = db.collection.find();
var totalSize = 0;
cursor.forEach(function(doc) {
totalSize += Object.bsonsize(doc);
});
print(totalSize);
Sample Data
db.sizeOfAllDocumentsDemo.insertMany([
{
"StudentFirstName": "John",
"StudentSubject": ["MongoDB", "Java"]
},
{
"StudentFirstName": "Larry",
"StudentSubject": ["MySQL", "PHP"],
"StudentAge": 21
},
{
"StudentFirstName": "Chris",
"StudentSubject": ["SQL Server", "C#"],
"StudentAge": 23,
"StudentCountryName": "US"
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd3c0c1edc6604c74817cd7"),
ObjectId("5cd3c0d9edc6604c74817cd8"),
ObjectId("5cd3c0fbedc6604c74817cd9")
]
}
Example: Calculate Total Documents Size
Let us calculate the cumulative size of all documents in the collection ?
var allDocument = db.sizeOfAllDocumentsDemo.find();
var counter = 0;
allDocument.forEach(
function(myDocument) {
counter = counter + Object.bsonsize(myDocument)
}
);
print(counter);
358
How It Works
-
find()returns a cursor to all documents in the collection -
forEach()iterates through each document in the cursor -
Object.bsonsize()returns the BSON size of each document in bytes - The sizes are accumulated in the counter variable
Conclusion
Use Object.bsonsize() with forEach() to calculate the total size of all documents returned by a MongoDB query. The result shows the cumulative BSON size in bytes.
Advertisements
