Executing a Command
The following guide will step you through the process of connecting to MongoDB and executing a command.
Prerequisites
Before you start this guide, ensure you have installed the driver and MongoDB is running on localhost. You can test that MongoDB is up and running by connecting to it with the MongoDB shell.
$ mongo --host localhost MongoDB shell version: 2.4.10 connecting to: localhost:27017/test >
The Basics
The following code example creates a new mongoc_client_t that we will use to communicate with MongoDB. See the Connection String URI page for more information on connecting to MongoDB.
Using our mongoc_client_t, we get a handle to a mongoc_collection_t which represents the remote collection. command is initialized to a new BSON document that contains all of the fields necessary to call the collStats command.
Use mongoc_collection_command() instead of mongoc_collection_command_simple() if you need a cursor returned from the command.
Lastly, we release all of our heap allocated structures.
example5.c
#include <bson.h> #include <bcon.h> #include <mongoc.h> #include <stdio.h> static void run_command (void) { mongoc_client_t *client; mongoc_collection_t *collection; bson_error_t error; bson_t *command; bson_t reply; char *str; client = mongoc_client_new ("mongodb://localhost:27017/"); collection = mongoc_client_get_collection (client, "test", "test"); command = BCON_NEW ("collStats", BCON_UTF8 ("test")); if (mongoc_collection_command_simple (collection, command, NULL, &reply, &error)) { str = bson_as_json (&reply, NULL); printf ("%s\n", str); bson_free (str); } else { fprintf (stderr, "Failed to run command: %s\n", error.message); } bson_destroy (command); bson_destroy (&reply); mongoc_collection_destroy (collection); mongoc_client_destroy (client); } int main (int argc, char *argv[]) { mongoc_init (); run_command (); mongoc_cleanup (); return 0; }
Let's use GCC and pkg-config to compile example5.c.
gcc -o example5 example5.c $(pkg-config --cflags --libs libmongoc-1.0)
When using the MongoDB C Driver, you must call mongoc_init() at the beginning of your application. This allows the driver to initialize it's required subsystems. Failure to do so will result in a runtime crash.
Now let's run it!
./example5 { "ns" : "test.test", "count" : 1, "size" : 24, "avgObjSize" : 24.000000, "storageSize" : 4096, "numExtents" : 1, "nindexes" : 1, "lastExtentSize" : 4096, "paddingFactor" : 1.000000, "systemFlags" : 1, "userFlags" : 0, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1.000000 }