如何找到占用大量空间的MongoDB集合的元素?

Zug*_*alt 2 size collections diskspace mongodb

如果我有一个包含数千个元素的集合,有没有一种方法可以让我轻松找到占用最多空间的元素(就MB而言)?

mil*_*lan 7

对此没有内置查询,您必须迭代集合,收集每个文档的大小,然后进行排序.这是它的工作方式:

var cursor = db.coll.find(); 
var doc_size = {}; 
cursor.forEach(function (x) { 
    var size = Object.bsonsize(x); 
    doc_size[x._id] = size;
});
Run Code Online (Sandbox Code Playgroud)

此时,您将拥有一个hashmap,其中文档ID为键,其大小为值.请注意,使用此方法,您将通过网络获取整个集合.另一种方法是使用MapReduce并执行此服务器端(在mongo内部):

> function mapper() {emit(this._id, Object.bsonsize(this));}
> function reducer(obj, size_in_b) { return { id : obj, size : size_in_b}; }
>
> var results = db.coll.mapReduce(mapper, reducer, {out : {inline : 1 }}).results
> results.sort(function(r1, r2) { return r2.value - r1.value; })
Run Code Online (Sandbox Code Playgroud)

inline:1告诉mongo不要为结果创建临时集合,所有内容都将保存在RAM中.

以及我的一个集合的示例输出:

[
    {
        "_id" : ObjectId("4ce9339942a812be22560634"),
        "value" : 1156115
    },
    {
        "_id" : ObjectId("4ce9340442a812be24560634"),
        "value" : 913413
    },
    {
        "_id" : ObjectId("4ce9340642a812be26560634"),
        "value" : 866833
    },
    {
        "_id" : ObjectId("4ce9340842a812be28560634"),
        "value" : 483614
    },
       ...
    {
        "_id" : ObjectId("4ce9340742a812be27560634"),
        "value" : 61268
    }
]
> 
Run Code Online (Sandbox Code Playgroud)