Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

javascript - How to get the size of single document in Mongodb?

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?

Here, I provide some code I perform testing on:

  1. I created new database 'test' and input simple document with only one attribute: type:"auto"

    db.test.insert({type:"auto"})
    
  2. output from stats() function call: db.test.stats():

    { 
      "ns" : "test.test",
      "count" : 1,
      "size" : 40,
      "avgObjSize" : 40,
      "storageSize" : 4096,
      "numExtents" : 1,
      "nindexes" : 1,
      "lastExtentSize" : 4096,
      "paddingFactor" : 1,
      "systemFlags" : 1,
      "userFlags" : 0,
      "totalIndexSize" : 8176,
      "indexSizes" : {
            "_id_" : 8176
    },
    "ok" : 1
    

    }

  3. output from bsonsize function call: Object.bsonsize(db.test.find({test:"auto"}))

    481
    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...