1

I want to get the size of the list of documents in mongodb.

db.getCollection('eventDetails').find({"dateTime" : { $gte : new ISODate("2018-05-01T12:00:00Z") },"dateTime" : { $lte : new ISODate("2018-05-31T23:59:59Z") }})

I want to get the size of the documents returned by the above mentioned query.

I tried the following query

var cursor = db.getCollection('eventDetails').find({"dateTime" : { $gte : new ISODate("2018-05-01T12:00:00Z") },"dateTime" : { $lte : new ISODate("2018-05-31T23:59:59Z") }})
var size = 0;
cursor.forEach(
    function(doc){
        size += Object.bsonsize(doc)
    }
);
print(size)

Each time execute the query, i get different results. Let me know how to get the size of the documents in mongodb

  • Have you checked the number of documents returned as well as they are not updated between your query execution? – Kapil Bhagchandani Aug 14 '18 at 8:53
  • Yes the database is not getting updated – user3138864 Aug 14 '18 at 9:06
  • Can you please update your code to reflect the documents returned each time you have executed the code along with output of size. I have tried the same on my collections and found the value of size unaffected. – Kapil Bhagchandani Aug 14 '18 at 9:19
  • @user3138864, What is MongoDB version(x,y,z)? – Md Haidar Ali Khan Aug 15 '18 at 7:01
0

As per MongoDB jira blog documentation Real document size in collection and also MongoDB documentation here the Object.bsonsize(<document>) prints the BSON size of a in bytes.

To find the size of all documents in a collection:

Object.bsonsize(db.collection.find( {dbname:"collectionname"}))

For Example

> use test
switched to db test
> db.createCollection("StackExchange");
{ "ok" : 1 }

> show collections
StackExchange
>

> db.StackExchange.insertOne({"Name" : "user3138864", "Password" : "abc123"})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5b740353194beb82d3752206")
}
> db.StackExchange.findOne()
{
        "_id" : ObjectId("5b740353194beb82d3752206"),
        "Name" : "user3138864",
        "Password" : "abc123"
}
> db.StackExchange.find().pretty()
{
        "_id" : ObjectId("5b740353194beb82d3752206"),
        "Name" : "user3138864",
        "Password" : "abc123"
}
> Object.bsonsize(db.StackExchange.find( {m040:"StackExchange"}))
45734

For further your ref here and here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.