Get the size of a collection in MongoDB using conditions?



Let us first create a collection with documents −

> dbmongoDBCollectionSizeDemoinsertOne({"Name":"John", "Age":23}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cf23e3db64a577be5a2bc16") } > dbmongoDBCollectionSizeDemoinsertOne({"Name":"Chris", "Age":24}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cf23e45b64a577be5a2bc17") } > dbmongoDBCollectionSizeDemoinsertOne({"Name":"Robert", "Age":26}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cf23e4db64a577be5a2bc18") }

Following is the query to display all documents from a collection with the help of find() method −

> dbmongoDBCollectionSizeDemofind();

This will produce the following document −

{ "_id" : ObjectId("5cf23e3db64a577be5a2bc16"), "Name" : "John", "Age" : 23 } { "_id" : ObjectId("5cf23e45b64a577be5a2bc17"), "Name" : "Chris", "Age" : 24 } { "_id" : ObjectId("5cf23e4db64a577be5a2bc18"), "Name" : "Robert", "Age" : 26 }

Following is the query to get the collection size using conditions −

> var collectionsize = 0; > dbmongoDBCollectionSizeDemofind({Name:'Robert'})forEach(function(d) {    var s = Objectbsonsize(d);    collectionsize=collectionsize +s; }) > print(collectionsize);

This will produce the following document −

52
Updated on: 2019-07-30T22:30:26+05:30

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements