HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Get the size of list of documents in mongo db

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thesizemongogetlistdocuments

Problem

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

Solution

As per MongoDB jira blog documentation Real document size in collection and also MongoDB documentation here the Object.bsonsize() 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

Code Snippets

Object.bsonsize(db.collection.find( {dbname:"collectionname"}))
> 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

Context

StackExchange Database Administrators Q#214854, answer score: 3

Revisions (0)

No revisions yet.