mongodb中db.mydb.find({tag:'java'}).count()和db.mydb.count({tag:'java'})的区别是什么

Fed*_*ico 2 mongodb

我需要在mondodb中快速计算大量文件(30 M)

db.mydb.find({tag:'java'}).count()和db.mydb.count({tag:'java'})的区别是什么

它比另一个更快?

我有标签索引.

谢谢,

费德里科.

bri*_*anz 6

这里有一个小技巧可以看看MongoDB命令在幕后做了什么:

> 
> db.mydb.count
function (x) {
    return this.find(x).count();
}
>
> db.mydb.find().count
function (applySkipLimit) {
    var cmd = {count:this._collection.getName()};
    if (this._query) {
        if (this._special) {
            cmd.query = this._query.query;
        } else {
            cmd.query = this._query;
        }
    }
    cmd.fields = this._fields || {};
    if (applySkipLimit) {
        if (this._limit) {
            cmd.limit = this._limit;
        }
        if (this._skip) {
            cmd.skip = this._skip;
        }
    }
    var res = this._db.runCommand(cmd);
    if (res && res.n != null) {
        return res.n;
    }
    throw "count failed: " + tojson(res);
}
Run Code Online (Sandbox Code Playgroud)

所以,是的,你可以看到这collection.count只是一个包装collection.find().count