Find the MongoDB collection size for name “Chris”

MongoDBDatabaseBig Data Analytics

For this, use bsonsize() in MongoDB. Let us create a collection with documents −

> db.demo250.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46bd501627c0c63e7dba70")
}
> db.demo250.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46bd531627c0c63e7dba71")
}
> db.demo250.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46bd561627c0c63e7dba72")
}
> db.demo250.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46bd5b1627c0c63e7dba73")
}

Display all documents from a collection with the help of find() method −

> db.demo250.find();

This will produce the following output −

{ "_id" : ObjectId("5e46bd501627c0c63e7dba70"), "Name" : "Chris" }
{ "_id" : ObjectId("5e46bd531627c0c63e7dba71"), "Name" : "Bob" }
{ "_id" : ObjectId("5e46bd561627c0c63e7dba72"), "Name" : "David" }
{ "_id" : ObjectId("5e46bd5b1627c0c63e7dba73"), "Name" : "Chris" }

Following is the query to find the MongoDB collection size for name “Chris” −

> var t = 0;
> db.demo250.find({Name:"Chris"}).forEach(function(doc) {
...   var s = Object.bsonsize(doc);
...   t += s;
... })
> print(t);

This will produce the following output in bytes −

76
raja
Published on 30-Mar-2020 14:11:15
Advertisements