To find the largest document size in MongoDB, you need to write a script in the shell.
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> 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") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.largestDocumentDemo.find().pretty();
The following is the output −
{ "_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 }
Here is the query to find the largest document size in MongoDB −
> 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 following is the output displaying the largest document size −
The Largest Document Size = 160