Run a Database Command
On this page
Overview
In this guide, you can learn how to run a database command with the C driver. You can use database commands to perform a variety of administrative and diagnostic tasks, such as fetching server statistics, initializing a replica set, or running an aggregation pipeline.
Important
Prefer Driver Functions to Database Commands
The driver provides wrapper functions for many database commands. We recommend using driver functions instead of executing database commands when possible.
To perform administrative tasks, use the MongoDB Shell instead
of the C driver. Calling the db.runCommand()
method inside the
shell is the preferred method to issue database commands, as it provides a
consistent interface between the shell and drivers.
Execute a Command
To run a database command, you must specify the command and any relevant parameters in a BSON document, then pass this BSON document to a command execution function. The C driver provides the following functions to run database commands:
mongoc_client_command_simple()
, which runs a specified command on the server and stores the first document from the result in thereply
BSON document. This function provides a simplified way to send a command directly to the server.mongoc_client_command_with_opts()
, which runs a specified command on the server and interpretsopts
according to the MongoDB server version. This function offers flexibilty by allowing additional options.
The following code shows how you can use the mongoc_client_command_simple()
function to run the hello
command, which returns information about the current
member's role in the replica set, on a database:
bson_t reply; bson_error_t error; bson_t *command = BCON_NEW ("hello", BCON_INT32 (1)); bool retval = mongoc_client_command_simple (client, "admin", command, NULL, &reply, &error); if (!retval) { fprintf (stderr, "Failed to run command: %s\n", error.message); } else { char *str = bson_as_canonical_extended_json (&reply, NULL); printf ("%s\n", str); bson_free (str); } bson_destroy (command); bson_destroy (&reply);
For a full list of database commands and corresponding parameters, see the Additional Information section.
Command Options
You can specify optional command behavior for the
mongoc_client_command_with_opts()
function. This function accepts a BSON
document for the opts
parameter.
You can pass a BSON document that specifies the following options:
readConcern
writeConcern
sessionId
collation
serverId
To learn more about a command and the options that it accepts, locate the command and follow the link in the Database Commands section of the Server manual.
The following code shows how to specify a grantRolesToUsers
command with a
majority
write concern:
bson_t reply; bson_error_t error; bson_t *command = BCON_NEW( "grantRolesToUser", BCON_UTF8("user011"), "roles", "[", BCON_UTF8("readWrite"), "]" ); mongoc_write_concern_t *write_concern = mongoc_write_concern_new(); mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY); bson_t *opts = bson_new(); mongoc_write_concern_append(write_concern, opts); bool retval = mongoc_client_command_with_opts(client, "admin", command, NULL, opts, &reply, &error); if (!retval) { fprintf(stderr, "Failed to run command: %s\n", error.message); } else { char *str = bson_as_canonical_extended_json(&reply, NULL); printf("Command Result: %s\n", str); bson_free(str); } bson_destroy(command); bson_destroy(opts); bson_destroy(&reply); mongoc_write_concern_destroy (write_concern);
Note
Read Preference
The mongoc_client_command_simple()
and
mongoc_client_command_with_opts()
functions ignore the read preference
setting you might have set on your client. By default, these functions use
the primary
read preference.
To specify a read preference other than the primary read preference, you must
explicity pass it as an argument. The following code demonstrates how to
specify a read preference and use it with the
mongoc_client_command_simple()
function:
read_prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY); command = BCON_NEW("hello", BCON_INT32(1)); retval = mongoc_client_command_simple(client, "admin", command, read_prefs, &reply, &error);
For more information on read preference options, see Read Preference in the Server manual.
Response
Each function returns either a BSON document or a cursor containing the response from the database after the command runs. Each database command performs a different function, so the response content can vary across commands. However, every response contains documents with the following fields:
<command result>
: Provides fields specific to the database command. For example,count
returns then
field andexplain
returns thequeryPlanner
field.ok
: Indicates whether the command succeeded (1
) or failed (0
).
Example
The following code shows how you can use the
mongoc_client_write_command_with_opts()
function to run the
cloneCollectionAsCapped
command with the writeConcern
option. It then
uses the mongoc_client_read_command_with_opts()
function to run the
distinct
command with the collation
and readConcern
options.
1 bson_t reply; 2 bson_error_t error; 3 4 bson_t *cmd = BCON_NEW ("cloneCollectionAsCapped", 5 BCON_UTF8 ("my_collection"), 6 "toCollection", 7 BCON_UTF8 ("my_capped_collection"), 8 "size", 9 BCON_INT64 (1024 * 1024)); 10 11 /* Includes write concern "majority" in command options */ 12 mongoc_write_concern_t *write_concern = mongoc_write_concern_new (); 13 mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY); 14 bson_t *opts = bson_new (); 15 mongoc_write_concern_append (write_concern, opts); 16 17 if (mongoc_client_write_command_with_opts (client, "test", cmd, opts, &reply, &error)) { 18 char *str = bson_as_canonical_extended_json (&reply, NULL); 19 printf ("cloneCollectionAsCapped: %s\n", str); 20 bson_free (str); 21 } else { 22 fprintf (stderr, "cloneCollectionAsCapped: %s\n", error.message); 23 } 24 25 bson_free (cmd); 26 bson_free (opts); 27 bson_destroy (&reply); 28 29 /* Defines distinct values of "x" in "my_collection" where "y" sorts after "one" */ 30 cmd = BCON_NEW ("distinct", 31 BCON_UTF8 ("my_collection"), 32 "key", 33 BCON_UTF8 ("x"), 34 "query", 35 "{", 36 "y", 37 "{", 38 "$gt", 39 BCON_UTF8 ("one"), 40 "}", 41 "}"); 42 43 mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); 44 45 /* Specifies "One" sorts after "one" to override default behavior */ 46 opts = BCON_NEW ("collation", "{", "locale", BCON_UTF8 ("en_US"), "caseFirst", BCON_UTF8 ("lower"), "}"); 47 48 /* Adds a read concern to "opts" */ 49 mongoc_read_concern_t *read_concern = mongoc_read_concern_new (); 50 mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_MAJORITY); 51 mongoc_read_concern_append (read_concern, opts); 52 53 if (mongoc_client_read_command_with_opts (client, "test", cmd, read_prefs, opts, &reply, &error)) { 54 char* str = bson_as_canonical_extended_json (&reply, NULL); 55 printf ("distinct: %s\n", str); 56 bson_free (str); 57 } else { 58 fprintf (stderr, "distinct: %s\n", error.message); 59 } 60 61 bson_destroy (cmd); 62 bson_destroy (opts); 63 bson_destroy (&reply); 64 mongoc_read_prefs_destroy (read_prefs); 65 mongoc_read_concern_destroy (read_concern); 66 mongoc_write_concern_destroy (write_concern);
Output
The cloneCollectionAsCapped
command clones a collection as a capped
collection. Then, the distinct
command gets the distinct values of a field
with a given filter and collation. The example outputs the following result:
cloneCollectionAsCapped: { "ok": 1, ... } distinct: { "values": ["value1", "value2", "value3"], "ok": 1, ... }
Additional Information
For more information about the concepts in this guide, see the following documentation: