Để tìm document có kích thước lớn nhất (largest document size) trong MongoDB, bạn cần viết script trong shell sử dụng Object.bsonsize().
Ví dụ minh họa
Tạo collection và dữ liệu
> db.largestDocumentDemo.insertOne({"StudentName":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ed2e32f684a30fbdfd57d") }
> db.largestDocumentDemo.insertOne({"StudentName":"Carol","StudentAge":22,"StudentCountryName":"US","TechnicalSubject":["C","C++","Java","MySQL"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ed3282f684a30fbdfd57e") }
> db.largestDocumentDemo.insertOne({"StudentName":"Mike","StudentAge":22});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ed3382f684a30fbdfd57f") }
Xem dữ liệu
> 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
}
Script tìm document lớn nhất
> var largestDocumentSize = 0;
> var largestDoc = null;
> db.largestDocumentDemo.find().forEach(function(myObject) {
var currentDocumentSize = Object.bsonsize(myObject);
if(largestDocumentSize < currentDocumentSize) {
largestDocumentSize = currentDocumentSize;
largestDoc = myObject;
}
});
> print('The Largest Document Size = ' + largestDocumentSize);
> printjson(largestDoc);
The Largest Document Size = 160
{
"_id" : ObjectId("5c8ed3282f684a30fbdfd57e"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentCountryName" : "US",
"TechnicalSubject" : [ "C", "C++", "Java", "MySQL" ]
}
Giải thích
Object.bsonsize(document): Trả về kích thước BSON của document (bytes)- Duyệt qua tất cả document với
forEach() - Giữ lại document có size lớn nhất
Script hoàn chỉnh có thể tái sử dụng
function findLargestDocument(collectionName) {
var maxSize = 0;
var maxDoc = null;
db[collectionName].find().forEach(function(doc) {
var size = Object.bsonsize(doc);
if (size > maxSize) {
maxSize = size;
maxDoc = doc;
}
});
print("Collection: " + collectionName);
print("Largest document size: " + maxSize + " bytes");
print("Document:");
printjson(maxDoc);
return maxDoc;
}
// Sử dụng
findLargestDocument("largestDocumentDemo");
Lưu ý
- Kích thước BSON bao gồm cả field names, type markers, padding
- Giới hạn document MongoDB: 16MB (16,777,216 bytes)
- Script này quét toàn bộ collection → chậm trên collection lớn
- Có thể thêm
.limit(10000)để test nhanh
Cách khác: Dùng aggregation (MongoDB 4.4+)
db.collection.aggregate([
{ $project: { size: { $bsonSize: "$$ROOT" }, doc: "$$ROOT" } },
{ $sort: { size: -1 } },
{ $limit: 1 }
])
Cách này dùng server-side processing, nhanh hơn shell script trên collection lớn.