EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
MongoDB Developer
Atlas
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
Atlaschevron-right

Getting Started with MongoDB and C

Diego Freniche12 min read • Published Mar 24, 2023 • Updated Mar 24, 2023
AtlasC
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty

Getting Started with MongoDB and C

In this article we'll install the MongoDB C driver on macOS, and use this driver to write some sample console applications that can interact with your MongoDB data by performing basic CRUD operations. We'll use Visual Studio Code to type in the code and the command line to compile and run our programs. If you want to try it out now, all source code is in the GitHub repository.

Table of contents

Prerequisites

  1. A MongoDB Atlas account with a cluster created.
  2. The sample dataset loaded into the Atlas cluster (or you can modify the sample code to use your own database and collection).
  3. Your machine’s IP address whitelisted. Note: You can add 0.0.0.0/0 as the IP address, which should allow access from any machine. This setting is not recommended for production use.

VS Code, C extensions, Xcode

  1. We will use Visual Studio Code, available in macOS, Windows, and Linux, because it has official support for C code. Just download and install the appropriate version.
  2. We need the C extensions, which will be suggested when you open a C file for the first time. You can also open extensions and search for "C/C++" and install them. This will install several extensions: C/C++, C/C++ Themes, and CMake.
  3. The last step is to make sure we have a C compiler. For that, either install Xcode from the Mac App Store or run in a terminal:
Although we can use CMake to build our C applications (and you have detailed instructions on how to do it), we'll use VS Code to type our code in and the terminal to build and run our programs.

Installing the C driver

In macOS, if we have the package manager homebrew installed (which you should), then we just open a terminal and type in:
You can also download the source code and build the driver, but using brew is just way more convenient.

Configuring VS Code extensions

To make autocomplete work in VS Code, we need to change the extension's config to make sure it "sees" these new libraries installed. We want to change our INCLUDE_PATH to allow both IntelliSense to check our code while typing it and be able to build our app from VS Code.
To do that, from VS Code, open the .vscode hidden folder, and then click on c_cpp_properties.json and add these lines:
Now, open tasks.json and add these lines to the args array:
With these, we're telling VS Code where to find the MongoDB C libraries so it can compile and check our code as we type.

Hello World MongoDB!

The source code is available on GitHub.

Setting up the client and pinging MongoDB Atlas

Let’s start with a simple program that connects to the MongoDB Atlas cluster and pings the server. For that, we need to get the connection string (URI) to the cluster and add it in our code. The best way is to create a new environment variable with the key “MONGODB_URI” and value the connection string (URI). It’s a good practice to keep the connection string decoupled from the code, but in this example, for simplicity, we'll have our connection string hardcoded.
We include the MongoDB driver and send an "echo" command from our main function. This example shows us how to initialize the MongoDB C client, how to create a command, manipulate JSON (in this case, BCON, BSON C Object Notation), send a command, process the response and error, and release any memory used.

Compiling and running our code

Although we can use way more sophisticated methods to compile and run our code, as this is just a C source code file and we're using just a few dependencies, I'll just compile from command line using good ol' gcc:
To run the code, just call the built binary:
In the repo that accompanies this post, you'll find a shell script that builds and runs all examples in one go.

Connecting to the database and listing all collections

Now that we have the skeleton of a C app, we can start using our database. In this case, we'll connect to the database sample_mflix, and we'll list all collections there.
After connecting to the database, we list all connections with a simple for loop after getting all collection names with mongoc_database_get_collection_names.
The complete sample follows.
If we compile and run it, we'l get this output:

Creating a JSON object in C

Being a document-based database, creating JSON documents is crucial for any application that interacts with MongoDB. Being this is C code, we don't use JSON. Instead, we use BCON (BSON C Object Notation, as mentioned above). To create a new document, we call BCON_NEW, and to convert it into a C string, we call bson_as_canonical_extended_json.

CRUD in MongoDB using the C driver

Now that we've covered the basics of connecting to MongoDB, let's have a look at how to manipulate data.

Querying data

Probably the most used function of any database is to retrieve data fast. In most use cases, we spend way more time accessing data than inserting or updating that same data. In this case, after creating our MongoDB client connection, we call mongoc_collection_find_with_opts, which will find data based on a query we can pass in. Once we have results, we can iterate through the returned cursor and do something with that data:
The complete sample follows.

Inserting a new document

OK, we know how to read data, but how about inserting fresh data in our MongoDB database? It's easy! We just create a BSON document to be inserted and call mongoc_collection_insert_one.
The complete sample follows.

Deleting a document

To delete a document, we call mongoc_collection_delete_one. We need to pass in a document containing the query to restrict the documents we want to find and delete.
The complete sample follows.

Updating a document

Finally, to update a document, we need to provide the query to find the document to update and a document with the fields we want to change.
The complete sample follows.

Wrapping up

With this article, we covered the installation of the MongoDB C driver, configuring VS Code as our editor and setting up other tools. Then, we created a few console applications that connect to MongoDB Atlas and perform basic CRUD operations.
Get more information about the C driver, and to try this code, the easiest way would be to register for a free MongoDB account. We can't wait to see what you build next!

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial

Next Gen Web Apps with Remix and MongoDB Atlas Data API


Feb 11, 2024 | 10 min read
Article

How to Build Serverless Applications with SST and MongoDB Atlas


Jan 23, 2024 | 3 min read
Tutorial

Application Deployment in Kubernetes with the MongoDB Atlas Operator


Apr 02, 2024 | 9 min read
Tutorial

Tutorial: Build a Movie Search Application Using Atlas Search


Sep 15, 2023 | 11 min read
Table of Contents