In this question I'm referring to Database commands and JavaScript methods.
I wonder why MongoDB has 2 different sets of operations for commands and methods. First I though that commands are a subset of operations available in JavaScript, but then I realized that there are commands like filemd5 which are not [directly] available as methods.
My question is why there is a distinction between commands and methods and why they cannot simply be the same set of operations having different representations. The command one is more suitable for declarative operations (for example available via REST) and the second is appropriate for DB scripting.
query in mongoshell returned a cursor, while database command returned an document that always has "ok" status, and one or more information.
To run a command against the current database, use db.runCommand() db. runCommand( { <command> } ) To run an administrative command against the admin database, use db.adminCommand() db.
The JavaScript methods can be seen as abstraction layer. Many methods are just wrappers for database commands. You can introspect the methods by just writing the function name without ()
.
Example:
> db.stats
function (scale) {
return this.runCommand({dbstats:1, scale:scale});
}
Some methods execute multiple commands and aggregate the output. Example:
> db.printCollectionStats
function () {
var mydb = this;
this.getCollectionNames().forEach(function (z)
{print(z);printjson(mydb.getCollection(z).stats());print("---");});
}
Some methods like find
, update
, delete
etc. do not call commands:
> db.coll.find
function (query, fields, limit, skip) {
return new DBQuery(this._mongo, this._db, this, this._fullName, this._massageObject(query), fields, limit, skip);
}
The MongoDB wire protocol specifies different request opcodes for query
, insert
, update
, delete
, getmore
, killcursors
etc.
Commands could have been implemented using different request opcodes. However, the MongoDB authors decided to implement commands as regular queries on a special collection called $cmd
.
The introspection of runCommand
reveals it:
> db.runCommand
function (obj) {
if (typeof obj == "string") {
var n = {};
n[obj] = 1;
obj = n;
}
return this.getCollection("$cmd").findOne(obj);
}
Some commands are internal and not intended to be called by the user. Hence, no method is offered in the MongoDB shell to conveniently access those commands.
A few examples:
_recvChunkAbort
_recvChunkCommit
_recvChunkStart
replSetHeartbeat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With