3

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

2
  • Yes the database is not getting updated Aug 14, 2018 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. Aug 14, 2018 at 9:19

1 Answer 1

3

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 <document> 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

1
  • the mongodb.com/docs links in this post are stale… does anybody have an up-to-date link? Oct 12, 2022 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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