JavaScript 方法
JavaScript 方法 可以被看作是抽象层。许多方法只是数据库命令的包装器。您可以通过写函数名称而不带 ()
来检查方法。
例如:
> db.stats
function (scale) {
return this.runCommand({dbstats:1, scale:scale});
}
有些方法会执行多个命令并聚合输出。例如:
> db.printCollectionStats
function () {
var mydb = this;
this.getCollectionNames().forEach(function (z)
{print(z);printjson(mydb.getCollection(z).stats());print("---");});
}
JavaScript方法与数据库命令的区别
一些方法(例如find
、update
、delete
等)并不调用命令:
> db.coll.find
function (query, fields, limit, skip) {
return new DBQuery(this._mongo, this._db, this, this._fullName, this._massageObject(query), fields, limit, skip);
}
MongoDB wire protocol 定义了不同的请求操作码(request opcodes),如 query
, insert
, update
, delete
, getmore
, killcursors
等。
命令可以使用不同的请求操作码来实现。然而,MongoDB 的作者决定将命令作为对一个特殊集合(称为 $cmd
)的常规查询(regular queries)来实现。
runCommand
的内省揭示了它的实现方式:
> db.runCommand
function (obj) {
if (typeof obj == "string") {
var n = {};
n[obj] = 1;
obj = n;
}
return this.getCollection("$cmd").findOne(obj);
}
内部命令
有些命令是内部命令,不打算让用户调用。因此,在MongoDB shell中没有提供方便地访问这些命令的方法。
以下是一些示例: