How to get the size of single document in Mongodb?

user1949763 picture user1949763 · Feb 25, 2014 · Viewed 75.4k times · Source

I encountered a strange behavior of mongo and I would like to clarify it a bit...
My request is simple as that: I would like to get a size of single document in collection. I found two possible solutions:

  • Object.bsonsize - some javascript method that should return a size in bytes
  • db.collection.stats() - where there is a line 'avgObjSize' that produce some "aggregated"(average) size view on the data. It simply represents average size of single document.

  • When I create test collection with only one document, both functions returns different values. How is it possible?
    Does it exist some other method to get a size of a mongo document?

Answer

user1949763 picture user1949763 · Mar 4, 2014

In the previous call of Object.bsonsize(), Mongodb returned the size of the cursor, rather than the document.

Correct way is to use this command:

Object.bsonsize(db.test.findOne())

With findOne(), you can define your query for a specific document:

Object.bsonsize(db.test.findOne({type:"auto"}))

This will return the correct size (in bytes) of the particular document.