Tushar Mishra
Tushar Mishra

Reputation: 1400

MongoDB - totalSize of a collection

Assume a collection name test has the following data

{ a : 1}
{ a : 2}

Also, it is indexed on {a : 1}

> db.test.stats()
{
    "ns" : "mydb.test",
    "count" : 2,
    "size" : 96,
    "avgObjSize" : 48,
    "storageSize" : 8192,
    "numExtents" : 1,
    "nindexes" : 2,
    "lastExtentSize" : 8192,
    "paddingFactor" : 1,
    "systemFlags" : 1,
    "userFlags" : 1,
    "totalIndexSize" : 16352,
    "indexSizes" : {
            "_id_" : 8176,
            "a_1" : 8176
    },
    "ok" : 1
}

> db.test.totalSize()
24544

As per documentation - it returns The total size of the data in the collection plus the size of every indexes on the collection. How ? From the data above,

total size of the data -> "size" : 96

size of every indexes -> 8176 * 2 -> 16392

Total -> 16392 + 96 = 16488

Why is there a difference ? What am I missing ?

Upvotes: 1

Views: 1643

Answers (1)

Philipp
Philipp

Reputation: 69703

The totalSize is equal to storageSize + totalIndexSize. As you will notice, these add up to exactly 24544.

To avoid constant reallocation of new hard-drive space and the resulting filesystem fragmentation when new documents are added to a collection, MongoDB overallocates storage space for each collection in advance. As a result, the total space used by a collection is always larger than the sum of its data.

Upvotes: 1

Related Questions