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
Find largest document size in MongoDB?
To find the largest document size in MongoDB, you need to iterate through all documents in a collection and use the Object.bsonsize() function to calculate each document's size in bytes.
Syntax
var largestSize = 0;
db.collection.find().forEach(function(doc) {
var currentSize = Object.bsonsize(doc);
if (largestSize < currentSize) {
largestSize = currentSize;
}
});
print("Largest Document Size = " + largestSize);
Sample Data
Let us create a collection with documents of varying sizes ?
db.largestDocumentDemo.insertMany([
{"StudentName": "John"},
{
"StudentName": "Carol",
"StudentAge": 22,
"StudentCountryName": "US",
"TechnicalSubject": ["C", "C++", "Java", "MySQL"]
},
{"StudentName": "Mike", "StudentAge": 22}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8ed2e32f684a30fbdfd57d"),
ObjectId("5c8ed3282f684a30fbdfd57e"),
ObjectId("5c8ed3382f684a30fbdfd57f")
]
}
Verify Sample Data
db.largestDocumentDemo.find().pretty();
{ "_id" : ObjectId("5c8ed2e32f684a30fbdfd57d"), "StudentName" : "John" }
{
"_id" : ObjectId("5c8ed3282f684a30fbdfd57e"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentCountryName" : "US",
"TechnicalSubject" : [
"C",
"C++",
"Java",
"MySQL"
]
}
{
"_id" : ObjectId("5c8ed3382f684a30fbdfd57f"),
"StudentName" : "Mike",
"StudentAge" : 22
}
Find Largest Document Size
var largestDocumentSize = 0;
db.largestDocumentDemo.find().forEach(function(myObject) {
var currentDocumentSize = Object.bsonsize(myObject);
if (largestDocumentSize < currentDocumentSize) {
largestDocumentSize = currentDocumentSize;
}
});
print("The Largest Document Size = " + largestDocumentSize);
The Largest Document Size = 160
How It Works
-
Object.bsonsize()returns the size of a document in bytes when stored in BSON format - The
forEach()method iterates through each document in the collection - We compare each document size and store the largest value found
Conclusion
Use Object.bsonsize() with a forEach() loop to find the largest document size in a MongoDB collection. This method calculates the actual BSON storage size of each document and returns the maximum value in bytes.
Advertisements
