Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีหา Document ขนาดใหญ่ที่สุดใน MongoDB

หา Document ที่มีขนาดใหญ่ที่สุดด้วย Shell Script

ใช้ Object.bsonsize() วัดขนาด Document แล้วเปรียบเทียบหาค่าสูงสุด

สร้างข้อมูลตัวอย่าง

> 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") }

Script หา Document ขนาดใหญ่ที่สุด

> 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

Document ของ Carol มีขนาดใหญ่ที่สุด (160 bytes) เพราะมี Field และ Array มากที่สุด