如何在Mongodb中获取单个文档的大小? [英] How to get the size of single document in Mongodb?

查看:1602
本文介绍了如何在Mongodb中获取单个文档的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了mongo的奇怪行为,我想澄清一下...
我的要求很简单:我希望在集合中获得单个文档的大小. 我找到了两种可能的解决方案:

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-一些应返回以字节为单位的大小的javascript方法
  • db.collection.stats()-其中有一行"avgObjSize",可在数据上生成一些汇总的"(平均)大小视图.它只代表单个文档的平均大小.

  • 当我仅使用一个文档创建测试集合时,两个函数都返回不同的值.这怎么可能?
    是否存在其他方法来获取mongo文档的大小?
  • 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. 我创建了新的数据库"test",并输入仅具有一个属性的简单文档:type:"auto"

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

db.test.insert({type:"auto"})

stats()函数调用的

  • 输出: db.test.stats():

  • 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
    

    }

    输出: Object.bsonsize(db.test.find({test:"auto"}))

    481
    

  • 推荐答案

    在上一个Object.bsonsize()调用中,Mongodb返回了游标的大小,而不是文档的大小.

    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())
    

    使用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.

    这篇关于如何在Mongodb中获取单个文档的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆