Connect to MongoDB
Create a project directory
In your shell, navigate to where you want to create your
application, then run the following command to create a
directory called c-quickstart
for this project:
mkdir c-quickstart
Select the tab corresponding to your operating system and run the
following commands to create a quickstart.c
application file
in the c-quickstart
directory:
cd c-quickstart touch quickstart.c
cd c-quickstart type nul > quickstart.c
Create your C driver application
Copy and paste the following code into the quickstart.c
file, which queries
the movies
collection in the sample_mflix
database:
int main (void) { const bson_t *doc; mongoc_init (); mongoc_client_t *client = mongoc_client_new ("<connection string>"); mongoc_collection_t *collection = mongoc_client_get_collection (client, "sample_mflix", "movies"); // Specify the query filter bson_t *query = BCON_NEW ("title", "The Shawshank Redemption"); mongoc_cursor_t *results = mongoc_collection_find_with_opts (collection, query, NULL, NULL); // Print the results while (mongoc_cursor_next (results, &doc)) { char* str = bson_as_canonical_extended_json (doc, NULL); printf ("%s\n", str); bson_free (str); } bson_destroy (query); mongoc_cursor_destroy (results); mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_cleanup (); return EXIT_SUCCESS; }
Assign the connection string
Replace the <connection string>
placeholder with the
connection string that you copied from the Create a Connection String
step of this guide.
Run your C application
In your shell, run the following commands to compile and run this application:
gcc -o quickstartc quickstart.c $(pkg-config --libs --cflags libmongoc-1.0) ./quickstartc
The command line output contains details about the retrieved movie document:
{ "_id" : { "$oid" : "..." }, "plot" : "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", ... "title" : "The Shawshank Redemption", ...
If you encounter an error or see no output, ensure that you specified the
proper connection string in the quickstart.c
file and that you loaded the
sample data.
After you complete these steps, you have a working application that uses the driver to connect to your MongoDB deployment, runs a query on the sample data, and prints out the result.
Note
If you run into issues on this step, ask for help in the MongoDB Community Forums or submit feedback by using the Rate this page tab on the right or bottom right side of this page.