Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run MongoDB commands by querying the special $cmd collection?

Tags:

mongodb

I'm trying to implement a MongoDB driver (actually I'm not implementing it from scratch, I'm improving an existing small one, but that's irrelevant). Issuing commands to MongoDB appears to simply be performed via special queries to the $cmd collection. This is described in the MongoDB glossary as follows:

$cmd

A special virtual collection that exposes MongoDB’s database commands. To use database commands, see Issue Commands.

Okay. So how do I do that? How about looking at Use Database Commands?

Many drivers provide an equivalent for the db.runCommand() method. Internally, running commands with db.runCommand() is equivalent to a special query against the $cmd collection.

Um, okay. That's not helpful. I'm writing a driver, not using one.

Is there documentation somewhere for how to actually implement runCommand functionality? How are the queries against $cmd supposed to work?

like image 570
Alexis King Avatar asked Nov 09 '22 18:11

Alexis King


1 Answers

How are the queries against $cmd supposed to work?

A database command is a query on a special collection, $cmd, where the query selector defines the command itself. So, query equivalent for running a command using db.runCommand({isMaster: 1}) is:

db.$cmd.findOne({isMaster: 1})

In my machine, they both generated the following result:

{
        "ismaster" : true,
        "maxBsonObjectSize" : 16777216,
        "maxMessageSizeBytes" : 48000000,
        "maxWriteBatchSize" : 1000,
        "localTime" : ISODate("2016-04-22T12:46:02.378Z"),
        "maxWireVersion" : 4,
        "minWireVersion" : 0,
        "ok" : 1
}
like image 117
Ali Dehghani Avatar answered Nov 15 '22 12:11

Ali Dehghani