How to get Index and data size in mongoDB?

Connect with

MongoDBAlthough there are different way of getting index size and data size in mongDB. I’m trying to explain the different way of doing this.

1. Calculate size of document(s)

Syntax:

> Object.bsonsize({username:"user101"})

Output:

> Object.bsonsize({username:"user101"})
27
> Object.bsonsize({_id:""+ObjectId()})
39
> Object.bsonsize({_id:ObjectId()})
22
> Object.bsonsize(db.user.find())
709
> Object.bsonsize(db.user.findOne())
85

2. Getting size of index and data on a collection

it returns in bytes. you can provide the scaling factor to calculate index size and data size:

Syntax

> db.collection.stats();

Output

> use training;
switched to db training
> show collections;
system.indexes
user
> db.user.stats();
{
        "ns" : "training.user",
        "count" : 1000000,
        "size" : 112000000,
        "avgObjSize" : 112,
        "storageSize" : 174735360,
        "numExtents" : 12,
        "nindexes" : 1,
        "lastExtentSize" : 50798592,
        "paddingFactor" : 1,
        "systemFlags" : 1,
        "userFlags" : 1,
        "totalIndexSize" : 32458720,
        "indexSizes" : {
                "_id_" : 32458720
        },
        "ok" : 1
}
>

3. Get size of index and data with scaling factor

this is used to get size of data and index on user collection.

For KB (kilobytes)

db.user.stats(1024)

for MB:

 db.user.stats(1024*1024);

for GB:

 db.user.stats(1024*1024*1024);

for TB:

 db.user.stats(1024*1024*1024*1024);

4. Get size of index only

It returns size of index only in bytes.

db.user.totalIndexSize();

5. Get storage size for all dbs using db.stats()

By defualt it returns in bytes, you can provide the scaling factor:
– for KB: 1024,
– for MB: 1024*1024,
– for GB: 1024*1024*1024

> db.stats();
{
        "db" : "training",
        "collections" : 3,
        "objects" : 1000004,
        "avgObjSize" : 111.999808000768,
        "dataSize" : 112000256,
        "storageSize" : 174751744,
        "numExtents" : 14,
        "indexes" : 1,
        "indexSize" : 32458720,
        "fileSize" : 469762048,
        "nsSizeMB" : 16,
        "dataFileVersion" : {
                "major" : 4,
                "minor" : 5
        },
        "extentFreeList" : {
                "num" : 0,
                "totalSize" : 0
        },
        "ok" : 1
}
>

6. Get storage size for all dbs

Get storage size of all database by show dbs;

> show dbs;
admin                 0.078GB
local                10.073GB
test                  0.078GB
training              0.453GB

Storage size of all data

You can use linux du command to know the storage size of all database.

[root@ranjeetJha~]# du -sh /var/lib/mongo/
117G    /var/lib/mongo/

Your suggestions are welcome to improve the post.


Connect with

2 thoughts on “How to get Index and data size in mongoDB?

Leave a Reply

Your email address will not be published. Required fields are marked *