Provided by: libmongoc-doc_1.21.0-1build1_all 

NAME
mongoc_reference - Index
LIBMONGOC
A Cross Platform MongoDB Client Library for C
Introduction
The MongoDB C Driver, also known as "libmongoc", is a library for using MongoDB from C applications, and
for writing MongoDB drivers in higher-level languages.
It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.
Installing the MongoDB C Driver (libmongoc) and BSON library (libbson)
The following guide will step you through the process of downloading, building, and installing the
current release of the MongoDB C Driver (libmongoc) and BSON library (libbson).
Supported Platforms
The MongoDB C Driver is continuously tested on a variety of platforms including:
• Archlinux
• Debian 9.2, 10.0
• macOS 10.14
• Microsoft Windows Server 2008, 2016
• RHEL 6.2, 7.0, 7.1, 8.2
• Ubuntu 16.04, 18.04
• Clang 3.4, 3.5, 3.7, 3.8, 6.0
• GCC 4.8, 4.9, 5.4, 6.3, 8.2, 8.3
• MinGW-W64
• Visual Studio 2013, 2015, 2017
• x86, x86_64, ARM (aarch64), Power8 (ppc64le), zSeries (s390x)
Install libmongoc with a Package Manager
Several Linux distributions provide packages for libmongoc and its dependencies. One advantage of
installing libmongoc with a package manager is that its dependencies (including libbson) will be
installed automatically. If you choose to install libmongoc from distribution packages, use the package
manager to confirm the version being installed is sufficient for your needs.
The libmongoc package is available on recent versions of Debian and Ubuntu.
$ apt-get install libmongoc-1.0-0
On Fedora, a mongo-c-driver package is available in the default repositories and can be installed with:
$ dnf install mongo-c-driver
On recent Red Hat systems, such as CentOS and RHEL 7, a mongo-c-driver package is available in the EPEL
repository. To check which version is available, see
https://apps.fedoraproject.org/packages/mongo-c-driver. The package can be installed with:
$ yum install mongo-c-driver
On macOS systems with Homebrew, the mongo-c-driver package can be installed with:
$ brew install mongo-c-driver
Install libbson with a Package Manager
The libbson package is available on recent versions of Debian and Ubuntu. If you have installed
libmongoc, then libbson will have already been installed as a dependency. It is also possible to install
libbson without libmongoc.
$ apt-get install libbson-1.0-0
On Fedora, a libbson package is available in the default repositories and can be installed with:
$ dnf install libbson
On recent Red Hat systems, such as CentOS and RHEL 7, a libbson package is available in the EPEL
repository. To check which version is available, see https://apps.fedoraproject.org/packages/libbson.
The package can be installed with:
$ yum install libbson
Build environment
Build environment on Unix
Prerequisites for libmongoc
OpenSSL is required for authentication or for TLS connections to MongoDB. Kerberos or LDAP support
requires Cyrus SASL.
To install all optional dependencies on RedHat / Fedora:
$ sudo yum install cmake openssl-devel cyrus-sasl-devel
On Debian / Ubuntu:
$ sudo apt-get install cmake libssl-dev libsasl2-dev
On FreeBSD:
$ su -c 'pkg install cmake openssl cyrus-sasl'
Prerequisites for libbson
The only prerequisite for building libbson is cmake. The command lines above can be adjusted to install
only cmake.
Build environment on macOS
Install the XCode Command Line Tools:
$ xcode-select --install
The cmake utility is also required. First install Homebrew according to its instructions, then:
$ brew install cmake
Build environment on Windows with Visual Studio
Building on Windows requires Windows Vista or newer and Visual Studio 2010 or newer. Additionally, cmake
is required to generate Visual Studio project files. Installation of these components on Windows is
beyond the scope of this document.
Build environment on Windows with MinGW-W64 and MSYS2
Install MSYS2 from msys2.github.io. Choose the x86_64 version, not i686.
Open the MingGW shell with c:\msys64\ming64.exe (not the msys2_shell). Install dependencies:
$ pacman --noconfirm -Syu
$ pacman --noconfirm -S mingw-w64-x86_64-gcc mingw-w64-x86_64-cmake
$ pacman --noconfirm -S mingw-w64-x86_64-extra-cmake-modules make tar
$ pacman --noconfirm -S mingw64/mingw-w64-x86_64-cyrus-sasl
Configuring the build
Before building libmongoc and/or libbson, it is necessary to configure, or prepare, the build. The steps
to prepare the build depend on how you obtained the source code and the build platform.
Preparing a build from a release tarball
The most recent release of libmongoc and libbson, both of which are included in mongo-c-driver, can be
downloaded here. The instructions in this document utilize cmake's out-of-source build feature to keep
build artifacts separate from source files. While the $ prompt is used throughout, the instructions below
will work on Linux, macOS, and Windows (assuming that CMake is in the user's shell path in all cases).
See the subsequent sections for additional platform-specific instructions.
The following snippet will download and extract the driver, and configure it:
$ wget https://github.com/mongodb/mongo-c-driver/releases/download/1.21.0/mongo-c-driver-1.21.0.tar.gz
$ tar xzf mongo-c-driver-1.21.0.tar.gz
$ cd mongo-c-driver-1.21.0
$ mkdir cmake-build
$ cd cmake-build
$ cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF ..
The -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF option is recommended, see init-cleanup. Another useful cmake
option is -DCMAKE_BUILD_TYPE=Release for a release optimized build and -DCMAKE_BUILD_TYPE=Debug for a
debug build. For a list of all configure options, run cmake -L ...
If cmake completed successfully, you will see a considerable amount of output describing your build
configuration. The final line of output should look something like this:
-- Build files have been written to: /home/user/mongo-c-driver-1.21.0/cmake-build
If cmake concludes with anything different, then it is likely an error occurred.
mongo-c-driver contains a copy of libbson, in case your system does not already have libbson installed.
The configuration will detect if libbson is not installed and use the bundled libbson.
Additionally, it is possible to build only libbson by setting the -DENABLE_MONGOC=OFF option:
$ cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF -DENABLE_MONGOC=OFF ..
A build configuration description similar to the one above will be displayed, though with fewer entries.
Once the configuration is complete, the selected items can be built and installed with these commands:
Preparing a build from a git repository clone
Clone the repository and prepare the build on the current branch or a particular release tag:
$ git clone https://github.com/mongodb/mongo-c-driver.git
$ cd mongo-c-driver
$ git checkout 1.21.0 # To build a particular release
$ python build/calc_release_version.py > VERSION_CURRENT
$ mkdir cmake-build
$ cd cmake-build
$ cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF ..
Preparing a build on Windows with Visual Studio
On the Windows platform with Visual Studio, it may be necessary to specify the CMake generator to use.
This is especially important if multiple versions of Visual Studio are installed on the system or if
alternate build tools (e.g., MinGW, MSYS2, Cygwin, etc.) are present on the system. Specifying the
generator will ensure that the build configuration is known with certainty, rather than relying on the
toolchain that CMake happens to find.
Start by generating Visual Studio project files. The following assumes you are compiling for 64-bit
Windows using Visual Studio 2015 Express, which can be freely downloaded from Microsoft. The sample
commands utilize cmake's out-of-source build feature to keep build artifacts separate from source files.
$ cd mongo-c-driver-1.21.0
$ mkdir cmake-build
$ cd cmake-build
$ cmake -G "Visual Studio 14 2015 Win64" \
"-DCMAKE_INSTALL_PREFIX=C:\mongo-c-driver" \
"-DCMAKE_PREFIX_PATH=C:\mongo-c-driver" \
..
(Run cmake -LH .. for a list of other options.)
To see a complete list of the CMake generators available on your specific system, use a command like
this:
$ cmake --help
Executing a build
Building on Unix, macOS, and Windows (MinGW-W64 and MSYS2)
$ cmake --build .
$ sudo cmake --build . --target install
(Note that the sudo command may not be applicable or available depending on the configuration of your
system.)
In the above commands, the first relies on the default target which builds all configured components.
For fine grained control over what gets built, the following command can be used (for Ninja and
Makefile-based build systems) to list all available targets:
$ cmake --build . help
Building on Windows with Visual Studio
Once the project files are generated, the project can be opened directly in Visual Studio or compiled
from the command line.
Build using the CMake build tool mode:
$ cmake --build . --config RelWithDebInfo
Visual Studio's default build type is Debug, but we recommend a release build with debug info for
production use. Now that libmongoc and libbson are compiled, install them. Components will be installed
to the path specified by CMAKE_INSTALL_PREFIX.
$ cmake --build . --config RelWithDebInfo --target install
You should now see libmongoc and libbson installed in C:\mongo-c-driver
For Visual Studio 2019 (16.4 and newer), this command can be used to list all available targets:
$ cmake --build . -- /targets
Alternately, you can examine the files matching the glob *.vcxproj in the cmake-build directory.
To use the driver libraries in your program, see visual-studio-guide.
Generating the documentation
Install Sphinx, then:
$ cmake -DENABLE_MAN_PAGES=ON -DENABLE_HTML_DOCS=ON ..
$ cmake --build . --target mongoc-doc
To build only the libbson documentation:
$ cmake -DENABLE_MAN_PAGES=ON -DENABLE_HTML_DOCS=ON ..
$ cmake --build . --target bson-doc
The -DENABLE_MAN_PAGES=ON and -DENABLE_HTML_DOCS=ON can also be added as options to a normal build from a
release tarball or from git so that the documentation is built at the same time as other components.
Uninstalling the installed components
There are two ways to uninstall the components that have been installed. The first is to invoke the
uninstall program directly. On Linux/Unix:
$ sudo /usr/local/share/mongo-c-driver/uninstall.sh
On Windows:
$ C:\mongo-c-driver\share\mongo-c-driver\uninstall.bat
The second way to uninstall is from within the build directory, assuming that it is in the exact same
state as when the install command was invoked:
$ sudo cmake --build . --target uninstall
The second approach simply invokes the uninstall program referenced in the first approach.
Dealing with Build Failures
If your attempt to build the C driver fails, please see the README
<https://github.com/mongodb/mongo-c-driver#how-to-ask-for-help> for instructions on requesting
assistance.
Additional Options for Integrators
In the event that you are building the BSON library and/or the C driver to embed with other components
and you wish to avoid the potential for collision with components installed from a standard build or from
a distribution package manager, you can make use of the BSON_OUTPUT_BASENAME and MONGOC_OUTPUT_BASENAME
options to cmake.
$ cmake -DBSON_OUTPUT_BASENAME=custom_bson -DMONGOC_OUTPUT_BASENAME=custom_mongoc ..
The above command would produce libraries named libcustom_bson.so and libcustom_mongoc.so (or with the
extension appropriate for the build platform). Those libraries could be placed in a standard system
directory or in an alternate location and could be linked to by specifying something like -lcustom_mongoc
-lcustom_bson on the linker command line (possibly adjusting the specific flags to those required by your
linker).
Tutorial
This guide offers a brief introduction to the MongoDB C Driver.
For more information on the C API, please refer to the api.
Contents
• Tutorial
• Installing
• Starting MongoDB
• Include and link libmongoc in your C program
• Use libmongoc in a Microsoft Visual Studio Project
• Making a Connection
• Creating BSON Documents
• Basic CRUD Operations
• Executing Commands
• Threading
• Next Steps
Installing
For detailed instructions on installing the MongoDB C Driver on a particular platform, please see the
installation guide.
Starting MongoDB
To run the examples in this tutorial, MongoDB must be installed and running on localhost on the default
port, 27017. To check if it is up and running, connect to it with the MongoDB shell.
$ mongo --host localhost --port 27017
MongoDB shell version: 3.0.6
connecting to: localhost:27017/test
>
Include and link libmongoc in your C program
Include mongoc.h
All libmongoc's functions and types are available in one header file. Simply include mongoc/mongoc.h:
#include <mongoc/mongoc.h>
CMake
The libmongoc installation includes a CMake config-file package, so you can use CMake's find_package
command to import libmongoc's CMake target and link to libmongoc (as a shared library):
CMakeLists.txt
# Specify the minimum version you require.
find_package (mongoc-1.0 1.7 REQUIRED)
# The "hello_mongoc.c" sample program is shared among four tests.
add_executable (hello_mongoc ../../hello_mongoc.c)
target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_shared)
You can also use libmongoc as a static library instead: Use the mongo::mongoc_static CMake target:
# Specify the minimum version you require.
find_package (mongoc-1.0 1.7 REQUIRED)
# The "hello_mongoc.c" sample program is shared among four tests.
add_executable (hello_mongoc ../../hello_mongoc.c)
target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_static)
pkg-config
If you're not using CMake, use pkg-config on the command line to set header and library paths:
gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-1.0)
Or to statically link to libmongoc:
gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-static-1.0)
Specifying header and include paths manually
If you aren't using CMake or pkg-config, paths and libraries can be managed manually.
$ gcc -o hello_mongoc hello_mongoc.c \
-I/usr/local/include/libbson-1.0 -I/usr/local/include/libmongoc-1.0 \
-lmongoc-1.0 -lbson-1.0
$ ./hello_mongoc
{ "ok" : 1.000000 }
For Windows users, the code can be compiled and run with the following commands. (This assumes that the
MongoDB C Driver has been installed to C:\mongo-c-driver; change the include directory as needed.)
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 hello_mongoc.c
C:\> hello_mongoc
{ "ok" : 1.000000 }
Use libmongoc in a Microsoft Visual Studio Project
See the libmongoc and Visual Studio guide.
Making a Connection
Access MongoDB with a mongoc_client_t. It transparently connects to standalone servers, replica sets and
sharded clusters on demand. To perform operations on a database or collection, create a mongoc_database_t
or mongoc_collection_t struct from the mongoc_client_t.
At the start of an application, call mongoc_init before any other libmongoc functions. At the end, call
the appropriate destroy function for each collection, database, or client handle, in reverse order from
how they were constructed. Call mongoc_cleanup before exiting.
The example below establishes a connection to a standalone server on localhost, registers the client
application as "connect-example," and performs a simple command.
More information about database operations can be found in the CRUD Operations and Executing Commands
sections. Examples of connecting to replica sets and sharded clusters can be found on the Advanced
Connections page.
hello_mongoc.c
#include <mongoc/mongoc.h>
int
main (int argc, char *argv[])
{
const char *uri_string = "mongodb://localhost:27017";
mongoc_uri_t *uri;
mongoc_client_t *client;
mongoc_database_t *database;
mongoc_collection_t *collection;
bson_t *command, reply, *insert;
bson_error_t error;
char *str;
bool retval;
/*
* Required to initialize libmongoc's internals
*/
mongoc_init ();
/*
* Optionally get MongoDB URI from command line
*/
if (argc > 1) {
uri_string = argv[1];
}
/*
* Safely create a MongoDB URI object from the given string
*/
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
/*
* Create a new client instance
*/
client = mongoc_client_new_from_uri (uri);
if (!client) {
return EXIT_FAILURE;
}
/*
* Register the application name so we can track it in the profile logs
* on the server. This can also be done from the URI (see other examples).
*/
mongoc_client_set_appname (client, "connect-example");
/*
* Get a handle on the database "db_name" and collection "coll_name"
*/
database = mongoc_client_get_database (client, "db_name");
collection = mongoc_client_get_collection (client, "db_name", "coll_name");
/*
* Do work. This example pings the database, prints the result as JSON and
* performs an insert
*/
command = BCON_NEW ("ping", BCON_INT32 (1));
retval = mongoc_client_command_simple (
client, "admin", command, NULL, &reply, &error);
if (!retval) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
str = bson_as_json (&reply, NULL);
printf ("%s\n", str);
insert = BCON_NEW ("hello", BCON_UTF8 ("world"));
if (!mongoc_collection_insert_one (collection, insert, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (insert);
bson_destroy (&reply);
bson_destroy (command);
bson_free (str);
/*
* Release our handles and clean up libmongoc
*/
mongoc_collection_destroy (collection);
mongoc_database_destroy (database);
mongoc_uri_destroy (uri);
mongoc_client_destroy (client);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
Creating BSON Documents
Documents are stored in MongoDB's data format, BSON. The C driver uses libbson to create BSON documents.
There are several ways to construct them: appending key-value pairs, using BCON, or parsing JSON.
Appending BSON
A BSON document, represented as a bson_t in code, can be constructed one field at a time using libbson's
append functions.
For example, to create a document like this:
{
born : ISODate("1906-12-09"),
died : ISODate("1992-01-01"),
name : {
first : "Grace",
last : "Hopper"
},
languages : [ "MATH-MATIC", "FLOW-MATIC", "COBOL" ],
degrees: [ { degree: "BA", school: "Vassar" }, { degree: "PhD", school: "Yale" } ]
}
Use the following code:
#include <bson/bson.h>
int
main (int argc,
char *argv[])
{
struct tm born = { 0 };
struct tm died = { 0 };
const char *lang_names[] = {"MATH-MATIC", "FLOW-MATIC", "COBOL"};
const char *schools[] = {"Vassar", "Yale"};
const char *degrees[] = {"BA", "PhD"};
uint32_t i;
char buf[16];
const char *key;
size_t keylen;
bson_t *document;
bson_t child;
bson_t child2;
char *str;
document = bson_new ();
/*
* Append { "born" : ISODate("1906-12-09") } to the document.
* Passing -1 for the length argument tells libbson to calculate the string length.
*/
born.tm_year = 6; /* years are 1900-based */
born.tm_mon = 11; /* months are 0-based */
born.tm_mday = 9;
bson_append_date_time (document, "born", -1, mktime (&born) * 1000);
/*
* Append { "died" : ISODate("1992-01-01") } to the document.
*/
died.tm_year = 92;
died.tm_mon = 0;
died.tm_mday = 1;
/*
* For convenience, this macro passes length -1 by default.
*/
BSON_APPEND_DATE_TIME (document, "died", mktime (&died) * 1000);
/*
* Append a subdocument.
*/
BSON_APPEND_DOCUMENT_BEGIN (document, "name", &child);
BSON_APPEND_UTF8 (&child, "first", "Grace");
BSON_APPEND_UTF8 (&child, "last", "Hopper");
bson_append_document_end (document, &child);
/*
* Append array of strings. Generate keys "0", "1", "2".
*/
BSON_APPEND_ARRAY_BEGIN (document, "languages", &child);
for (i = 0; i < sizeof lang_names / sizeof (char *); ++i) {
keylen = bson_uint32_to_string (i, &key, buf, sizeof buf);
bson_append_utf8 (&child, key, (int) keylen, lang_names[i], -1);
}
bson_append_array_end (document, &child);
/*
* Array of subdocuments:
* degrees: [ { degree: "BA", school: "Vassar" }, ... ]
*/
BSON_APPEND_ARRAY_BEGIN (document, "degrees", &child);
for (i = 0; i < sizeof degrees / sizeof (char *); ++i) {
keylen = bson_uint32_to_string (i, &key, buf, sizeof buf);
bson_append_document_begin (&child, key, (int) keylen, &child2);
BSON_APPEND_UTF8 (&child2, "degree", degrees[i]);
BSON_APPEND_UTF8 (&child2, "school", schools[i]);
bson_append_document_end (&child, &child2);
}
bson_append_array_end (document, &child);
/*
* Print the document as a JSON string.
*/
str = bson_as_canonical_extended_json (document, NULL);
printf ("%s\n", str);
bson_free (str);
/*
* Clean up allocated bson documents.
*/
bson_destroy (document);
return 0;
}
See the libbson documentation for all of the types that can be appended to a bson_t.
Using BCON
BSON C Object Notation, BCON for short, is an alternative way of constructing BSON documents in a manner
closer to the intended format. It has less type-safety than BSON's append functions but results in less
code.
#include <bson/bson.h>
int
main (int argc,
char *argv[])
{
struct tm born = { 0 };
struct tm died = { 0 };
bson_t *document;
char *str;
born.tm_year = 6;
born.tm_mon = 11;
born.tm_mday = 9;
died.tm_year = 92;
died.tm_mon = 0;
died.tm_mday = 1;
document = BCON_NEW (
"born", BCON_DATE_TIME (mktime (&born) * 1000),
"died", BCON_DATE_TIME (mktime (&died) * 1000),
"name", "{",
"first", BCON_UTF8 ("Grace"),
"last", BCON_UTF8 ("Hopper"),
"}",
"languages", "[",
BCON_UTF8 ("MATH-MATIC"),
BCON_UTF8 ("FLOW-MATIC"),
BCON_UTF8 ("COBOL"),
"]",
"degrees", "[",
"{", "degree", BCON_UTF8 ("BA"), "school", BCON_UTF8 ("Vassar"), "}",
"{", "degree", BCON_UTF8 ("PhD"), "school", BCON_UTF8 ("Yale"), "}",
"]");
/*
* Print the document as a JSON string.
*/
str = bson_as_canonical_extended_json (document, NULL);
printf ("%s\n", str);
bson_free (str);
/*
* Clean up allocated bson documents.
*/
bson_destroy (document);
return 0;
}
Notice that BCON can create arrays, subdocuments and arbitrary fields.
Creating BSON from JSON
For single documents, BSON can be created from JSON strings via bson_new_from_json.
#include <bson/bson.h>
int
main (int argc,
char *argv[])
{
bson_error_t error;
bson_t *bson;
char *string;
const char *json = "{\"name\": {\"first\":\"Grace\", \"last\":\"Hopper\"}}";
bson = bson_new_from_json ((const uint8_t *)json, -1, &error);
if (!bson) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
string = bson_as_canonical_extended_json (bson, NULL);
printf ("%s\n", string);
bson_free (string);
return 0;
}
To initialize BSON from a sequence of JSON documents, use bson_json_reader_t.
Basic CRUD Operations
This section demonstrates the basics of using the C Driver to interact with MongoDB.
Inserting a Document
To insert documents into a collection, first obtain a handle to a mongoc_collection_t via a
mongoc_client_t. Then, use mongoc_collection_insert_one to add BSON documents to the collection. This
example inserts into the database "mydb" and collection "mycoll".
When finished, ensure that allocated structures are freed by using their respective destroy functions.
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/?appname=insert-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "hello", "world");
if (!mongoc_collection_insert_one (
collection, doc, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
Compile the code and run it:
$ gcc -o insert insert.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./insert
On Windows:
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 insert.c
C:\> insert
To verify that the insert succeeded, connect with the MongoDB shell.
$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.find()
{ "_id" : ObjectId("55ef43766cb5f36a3bae6ee4"), "hello" : "world" }
>
Finding a Document
To query a MongoDB collection with the C driver, use the function mongoc_collection_find_with_opts().
This returns a cursor to the matching documents. The following examples iterate through the result
cursors and print the matches to stdout as JSON strings.
Use a document as a query specifier; for example,
{ "color" : "red" }
will match any document with a field named "color" with value "red". An empty document {} can be used to
match all documents.
This first example uses an empty query specifier to find all documents in the database "mydb" and
collection "mycoll".
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_t *query;
char *str;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=find-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
query = bson_new ();
cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_canonical_extended_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
bson_destroy (query);
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
Compile the code and run it:
$ gcc -o find find.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./find
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
On Windows:
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find.c
C:\> find
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
To look for a specific document, add a specifier to query. This example adds a call to BSON_APPEND_UTF8()
to look for all documents matching {"hello" : "world"}.
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_t *query;
char *str;
mongoc_init ();
client = mongoc_client_new (
"mongodb://localhost:27017/?appname=find-specific-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
query = bson_new ();
BSON_APPEND_UTF8 (query, "hello", "world");
cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_canonical_extended_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
bson_destroy (query);
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
$ gcc -o find-specific find-specific.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./find-specific
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find-specific.c
C:\> find-specific
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
Updating a Document
This code snippet gives an example of using mongoc_collection_update_one() to update the fields of a
document.
Using the "mydb" database, the following example inserts an example document into the "mycoll"
collection. Then, using its _id field, the document is updated with different values and a new field.
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_collection_t *collection;
mongoc_client_t *client;
bson_error_t error;
bson_oid_t oid;
bson_t *doc = NULL;
bson_t *update = NULL;
bson_t *query = NULL;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=update-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
bson_oid_init (&oid, NULL);
doc = BCON_NEW ("_id", BCON_OID (&oid), "key", BCON_UTF8 ("old_value"));
if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
goto fail;
}
query = BCON_NEW ("_id", BCON_OID (&oid));
update = BCON_NEW ("$set",
"{",
"key",
BCON_UTF8 ("new_value"),
"updated",
BCON_BOOL (true),
"}");
if (!mongoc_collection_update_one (
collection, query, update, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
goto fail;
}
fail:
if (doc)
bson_destroy (doc);
if (query)
bson_destroy (query);
if (update)
bson_destroy (update);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
Compile the code and run it:
$ gcc -o update update.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./update
On Windows:
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 update.c
C:\> update
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
To verify that the update succeeded, connect with the MongoDB shell.
$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.find({"updated" : true})
{ "_id" : ObjectId("55ef549236fe322f9490e17b"), "updated" : true, "key" : "new_value" }
>
Deleting a Document
This example illustrates the use of mongoc_collection_delete_one() to delete a document.
The following code inserts a sample document into the database "mydb" and collection "mycoll". Then, it
deletes all documents matching {"hello" : "world"}.
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=delete-example");
collection = mongoc_client_get_collection (client, "test", "test");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "hello", "world");
if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
fprintf (stderr, "Insert failed: %s\n", error.message);
}
bson_destroy (doc);
doc = bson_new ();
BSON_APPEND_OID (doc, "_id", &oid);
if (!mongoc_collection_delete_one (
collection, doc, NULL, NULL, &error)) {
fprintf (stderr, "Delete failed: %s\n", error.message);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
Compile the code and run it:
$ gcc -o delete delete.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./delete
On Windows:
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 delete.c
C:\> delete
Use the MongoDB shell to prove that the documents have been removed successfully.
$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.count({"hello" : "world"})
0
>
Counting Documents
Counting the number of documents in a MongoDB collection is similar to performing a find operation. This
example counts the number of documents matching {"hello" : "world"} in the database "mydb" and collection
"mycoll".
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
int64_t count;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=count-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new_from_json (
(const uint8_t *) "{\"hello\" : \"world\"}", -1, &error);
count = mongoc_collection_count (
collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);
if (count < 0) {
fprintf (stderr, "%s\n", error.message);
} else {
printf ("%" PRId64 "\n", count);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
Compile the code and run it:
$ gcc -o count count.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./count
1
On Windows:
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 count.c
C:\> count
1
Executing Commands
The driver provides helper functions for executing MongoDB commands on client, database and collection
structures. These functions return cursors; the _simple variants return booleans indicating success or
failure.
This example executes the collStats command against the collection "mycoll" in database "mydb".
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_t *command;
bson_t reply;
char *str;
mongoc_init ();
client = mongoc_client_new (
"mongodb://localhost:27017/?appname=executing-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
command = BCON_NEW ("collStats", BCON_UTF8 ("mycoll"));
if (mongoc_collection_command_simple (
collection, command, NULL, &reply, &error)) {
str = bson_as_canonical_extended_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);
mongoc_cleanup ();
return 0;
}
Compile the code and run it:
$ gcc -o executing executing.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./executing
{ "ns" : "mydb.mycoll", "count" : 1, "size" : 48, "avgObjSize" : 48, "numExtents" : 1, "storageSize" : 8192,
"lastExtentSize" : 8192.000000, "paddingFactor" : 1.000000, "userFlags" : 1, "capped" : false, "nindexes" : 1,
"indexDetails" : { }, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1.000000 }
On Windows:
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 executing.c
C:\> executing
{ "ns" : "mydb.mycoll", "count" : 1, "size" : 48, "avgObjSize" : 48, "numExtents" : 1, "storageSize" : 8192,
"lastExtentSize" : 8192.000000, "paddingFactor" : 1.000000, "userFlags" : 1, "capped" : false, "nindexes" : 1,
"indexDetails" : { }, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1.000000 }
Threading
The MongoDB C Driver is thread-unaware in the vast majority of its operations. This means it is up to the
programmer to guarantee thread-safety.
However, mongoc_client_pool_t is thread-safe and is used to fetch a mongoc_client_t in a thread-safe
manner. After retrieving a client from the pool, the client structure should be considered owned by the
calling thread. When the thread is finished, the client should be placed back into the pool.
example-pool.c
/* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs
* libmongoc-1.0) */
/* ./example-pool [CONNECTION_STRING] */
#include <mongoc/mongoc.h>
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mutex;
static bool in_shutdown = false;
static void *
worker (void *data)
{
mongoc_client_pool_t *pool = data;
mongoc_client_t *client;
bson_t ping = BSON_INITIALIZER;
bson_error_t error;
bool r;
BSON_APPEND_INT32 (&ping, "ping", 1);
while (true) {
client = mongoc_client_pool_pop (pool);
/* Do something with client. If you are writing an HTTP server, you
* probably only want to hold onto the client for the portion of the
* request performing database queries.
*/
r = mongoc_client_command_simple (
client, "admin", &ping, NULL, NULL, &error);
if (!r) {
fprintf (stderr, "%s\n", error.message);
}
mongoc_client_pool_push (pool, client);
pthread_mutex_lock (&mutex);
if (in_shutdown || !r) {
pthread_mutex_unlock (&mutex);
break;
}
pthread_mutex_unlock (&mutex);
}
bson_destroy (&ping);
return NULL;
}
int
main (int argc, char *argv[])
{
const char *uri_string = "mongodb://127.0.0.1/?appname=pool-example";
mongoc_uri_t *uri;
bson_error_t error;
mongoc_client_pool_t *pool;
pthread_t threads[10];
unsigned i;
void *ret;
pthread_mutex_init (&mutex, NULL);
mongoc_init ();
if (argc > 1) {
uri_string = argv[1];
}
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
pool = mongoc_client_pool_new (uri);
mongoc_client_pool_set_error_api (pool, 2);
for (i = 0; i < 10; i++) {
pthread_create (&threads[i], NULL, worker, pool);
}
sleep (10);
pthread_mutex_lock (&mutex);
in_shutdown = true;
pthread_mutex_unlock (&mutex);
for (i = 0; i < 10; i++) {
pthread_join (threads[i], &ret);
}
mongoc_client_pool_destroy (pool);
mongoc_uri_destroy (uri);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
Next Steps
To find information on advanced topics, browse the rest of the C driver guide or the official MongoDB
documentation.
For help with common issues, consult the Troubleshooting page. To report a bug or request a new feature,
follow these instructions.
Authentication
This guide covers the use of authentication options with the MongoDB C Driver. Ensure that the MongoDB
server is also properly configured for authentication before making a connection. For more information,
see the MongoDB security documentation.
The MongoDB C driver supports several authentication mechanisms through the use of MongoDB connection
URIs.
By default, if a username and password are provided as part of the connection string (and an optional
authentication database), they are used to connect via the default authentication mechanism of the
server.
To select a specific authentication mechanism other than the default, see the list of supported mechanism
below.
mongoc_client_t *client = mongoc_client_new ("mongodb://user:password@localhost/?authSource=mydb");
Currently supported values for the authMechanism connection string option are:
• SCRAM-SHA-1
• MONGODB-CR (deprecated)
• GSSAPI
• PLAIN
• X509
• MONGODB-AWS
Basic Authentication (SCRAM-SHA-256)
MongoDB 4.0 introduces support for authenticating using the SCRAM protocol with the more secure SHA-256
hash described in RFC 7677. Using this authentication mechanism means that the password is never actually
sent over the wire when authenticating, but rather a computed proof that the client password is the same
as the password the server knows. In MongoDB 4.0, the C driver can determine the correct default
authentication mechanism for users with stored SCRAM-SHA-1 and SCRAM-SHA-256 credentials:
mongoc_client_t *client = mongoc_client_new ("mongodb://user:password@localhost/?authSource=mydb");
/* the correct authMechanism is negotiated between the driver and server. */
Alternatively, SCRAM-SHA-256 can be explicitly specified as an authMechanism.
mongoc_client_t *client = mongoc_client_new ("mongodb://user:password@localhost/?authMechanism=SCRAM-SHA-256&authSource=mydb");
Passwords for SCRAM-SHA-256 undergo the preprocessing step known as SASLPrep specified in RFC 4013.
SASLPrep will only be performed for passwords containing non-ASCII characters. SASLPrep requires libicu.
If libicu is not available, attempting to authenticate over SCRAM-SHA-256 with non-ASCII passwords will
result in error.
Usernames never undergo SASLPrep.
By default, when building the C driver libicu is linked if available. This can be changed with the
ENABLE_ICU cmake option. To specify an installation path of libicu, specify ICU_ROOT as a cmake option.
See the FindICU documentation for more information.
Basic Authentication (SCRAM-SHA-1)
The default authentication mechanism before MongoDB 4.0 is SCRAM-SHA-1 (RFC 5802). Using this
authentication mechanism means that the password is never actually sent over the wire when
authenticating, but rather a computed proof that the client password is the same as the password the
server knows.
mongoc_client_t *client = mongoc_client_new ("mongodb://user:password@localhost/?authMechanism=SCRAM-SHA-1&authSource=mydb");
NOTE:
SCRAM-SHA-1 authenticates against the admin database by default. If the user is created in another
database, then specifying the authSource is required.
Legacy Authentication (MONGODB-CR)
The MONGODB-CR authMechanism is deprecated and will no longer function in MongoDB 4.0. Instead, specify
no authMechanism and the driver will use an authentication mechanism compatible with your server.
GSSAPI (Kerberos) Authentication
NOTE:
Kerberos support requires compiling the driver against cyrus-sasl on UNIX-like environments. On
Windows, configure the driver to build against the Windows Native SSPI.
GSSAPI (Kerberos) authentication is available in the Enterprise Edition of MongoDB. To authenticate using
GSSAPI, the MongoDB C driver must be installed with SASL support.
On UNIX-like environments, run the kinit command before using the following authentication methods:
$ kinit mongodbuser@EXAMPLE.COM
mongodbuser@EXAMPLE.COM's Password:
$ klistCredentials cache: FILE:/tmp/krb5cc_1000
Principal: mongodbuser@EXAMPLE.COM
Issued Expires Principal
Feb 9 13:48:51 2013 Feb 9 23:48:51 2013 krbtgt/EXAMPLE.COM@EXAMPLE.COM
Now authenticate using the MongoDB URI. GSSAPI authenticates against the $external virtual database, so a
database does not need to be specified in the URI. Note that the Kerberos principal must be URL-encoded:
mongoc_client_t *client;
client = mongoc_client_new ("mongodb://mongodbuser%40EXAMPLE.COM@mongo-server.example.com/?authMechanism=GSSAPI");
NOTE:
GSSAPI authenticates against the $external database, so specifying the authSource database is not
required.
The driver supports these GSSAPI properties:
• CANONICALIZE_HOST_NAME: This might be required with Cyrus-SASL when the hosts report different
hostnames than what is used in the Kerberos database. The default is "false".
• SERVICE_NAME: Use a different service name than the default, "mongodb".
Set properties in the URL:
mongoc_client_t *client;
client = mongoc_client_new ("mongodb://mongodbuser%40EXAMPLE.COM@mongo-server.example.com/?authMechanism=GSSAPI&"
"authMechanismProperties=SERVICE_NAME:other,CANONICALIZE_HOST_NAME:true");
If you encounter errors such as Invalid net address, check if the application is behind a NAT (Network
Address Translation) firewall. If so, create a ticket that uses forwardable and addressless Kerberos
tickets. This can be done by passing -f -A to kinit.
$ kinit -f -A mongodbuser@EXAMPLE.COM
SASL Plain Authentication
NOTE:
The MongoDB C Driver must be compiled with SASL support in order to use SASL PLAIN authentication.
MongoDB Enterprise Edition supports the SASL PLAIN authentication mechanism, initially intended for
delegating authentication to an LDAP server. Using the SASL PLAIN mechanism is very similar to the
challenge response mechanism with usernames and passwords. This authentication mechanism uses the
$external virtual database for LDAP support:
NOTE:
SASL PLAIN is a clear-text authentication mechanism. It is strongly recommended to connect to MongoDB
using TLS with certificate validation when using the PLAIN mechanism.
mongoc_client_t *client;
client = mongoc_client_new ("mongodb://user:password@example.com/?authMechanism=PLAIN");
PLAIN authenticates against the $external database, so specifying the authSource database is not
required.
X.509 Certificate Authentication
NOTE:
The MongoDB C Driver must be compiled with TLS support for X.509 authentication support. Once this is
done, start a server with the following options:
$ mongod --tlsMode requireTLS --tlsCertificateKeyFile server.pem --tlsCAFile ca.pem
The MONGODB-X509 mechanism authenticates a username derived from the distinguished subject name of the
X.509 certificate presented by the driver during TLS negotiation. This authentication method requires the
use of TLS connections with certificate validation.
mongoc_client_t *client;
mongoc_ssl_opt_t ssl_opts = { 0 };
ssl_opts.pem_file = "mycert.pem";
ssl_opts.pem_pwd = "mycertpassword";
ssl_opts.ca_file = "myca.pem";
ssl_opts.ca_dir = "trust_dir";
ssl_opts.weak_cert_validation = false;
client = mongoc_client_new ("mongodb://x509_derived_username@localhost/?authMechanism=MONGODB-X509");
mongoc_client_set_ssl_opts (client, &ssl_opts);
MONGODB-X509 authenticates against the $external database, so specifying the authSource database is not
required. For more information on the x509_derived_username, see the MongoDB server x.509 tutorial.
NOTE:
The MongoDB C Driver will attempt to determine the x509 derived username when none is provided, and as
of MongoDB 3.4 providing the username is not required at all.
Authentication via AWS IAM
The MONGODB-AWS mechanism authenticates to MongoDB servers with credentials provided by AWS Identity and
Access Management (IAM).
To authenticate, create a user with an associated Amazon Resource Name (ARN) on the $external database,
and specify the MONGODB-AWS authMechanism in the URI.
mongoc_uri_t *uri = mongoc_uri_new ("mongodb://localhost/?authMechanism=MONGODB-AWS");
Since MONGODB-AWS always authenticates against the $external database, so specifying the authSource
database is not required.
Credentials include the access key id, secret access key, and optional session token. They may be
obtained from the following ways.
AWS credentials via URI
Credentials may be passed directly in the URI as username/password.
mongoc_uri_t *uri = mongoc_uri_new ("mongodb://<access key id>:<secret access key>localhost/?authMechanism=MONGODB-AWS");
This may include a session token passed with authMechanismProperties.
mongoc_uri_t *uri = mongoc_uri_new ("mongodb://<access key id>:<secret access key>localhost/?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<token>");
AWS credentials via environment
If credentials are not passed through the URI, libmongoc will check for the following environment
variables.
• AWS_ACCESS_KEY_ID
• AWS_SECRET_ACCESS_KEY
• AWS_SESSION_TOKEN (optional)
AWS Credentials via ECS
If credentials are not passed in the URI or with environment variables, libmongoc will check if the
environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set, and if so, attempt to retrieve
temporary credentials from the ECS task metadata by querying a link local address.
AWS Credentials via EC2
If credentials are not passed in the URI or with environment variables, and the environment variable
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is not set, libmongoc will attempt to retrieve temporary
credentials from the EC2 machine metadata by querying link local addresses.
Basic Troubleshooting
Troubleshooting Checklist
The following is a short list of things to check when you have a problem.
• Did you call mongoc_init() in main()? If not, you will likely see a segfault.
• Have you leaked any clients or cursors as can be found with mongoc-stat <PID>?
• Have packets been delivered to the server? See egress bytes from mongoc-stat <PID>.
• Does valgrind show any leaks? Ensure you call mongoc_cleanup() at the end of your process to cleanup
lingering allocations from the MongoDB C driver.
• If compiling your own copy of MongoDB C Driver, consider using the cmake option -DENABLE_TRACING=ON to
enable function tracing and hex dumps of network packets to STDERR and STDOUT.
Performance Counters
The MongoDB C driver comes with an optional unique feature to help developers and sysadmins troubleshoot
problems in production. Performance counters are available for each process using the driver. If
available, the counters can be accessed outside of the application process via a shared memory segment.
This means that you can graph statistics about your application process easily from tools like Munin or
Nagios. Your author often uses watch --interval=0.5 -d mongoc-stat $PID to monitor an application.
Performance counters are only available on Linux platforms and macOS arm64 platforms supporting shared
memory segments. On supported platforms they are enabled by default. Applications can be built without
the counters by specifying the cmake option -DENABLE_SHM_COUNTERS=OFF. Additionally, if performance
counters are already compiled, they can be disabled at runtime by specifying the environment variable
MONGOC_DISABLE_SHM.
Performance counters keep track of the following:
• Active and Disposed Cursors
• Active and Disposed Clients, Client Pools, and Socket Streams.
• Number of operations sent and received, by type.
• Bytes transferred and received.
• Authentication successes and failures.
• Number of wire protocol errors.
To access counters for a given process, simply provide the process id to the mongoc-stat program
installed with the MongoDB C Driver.
$ mongoc-stat 22203
Operations : Egress Total : The number of sent operations. : 13247
Operations : Ingress Total : The number of received operations. : 13246
Operations : Egress Queries : The number of sent Query operations. : 13247
Operations : Ingress Queries : The number of received Query operations. : 0
Operations : Egress GetMore : The number of sent GetMore operations. : 0
Operations : Ingress GetMore : The number of received GetMore operations. : 0
Operations : Egress Insert : The number of sent Insert operations. : 0
Operations : Ingress Insert : The number of received Insert operations. : 0
Operations : Egress Delete : The number of sent Delete operations. : 0
Operations : Ingress Delete : The number of received Delete operations. : 0
Operations : Egress Update : The number of sent Update operations. : 0
Operations : Ingress Update : The number of received Update operations. : 0
Operations : Egress KillCursors : The number of sent KillCursors operations. : 0
Operations : Ingress KillCursors : The number of received KillCursors operations. : 0
Operations : Egress Msg : The number of sent Msg operations. : 0
Operations : Ingress Msg : The number of received Msg operations. : 0
Operations : Egress Reply : The number of sent Reply operations. : 0
Operations : Ingress Reply : The number of received Reply operations. : 13246
Cursors : Active : The number of active cursors. : 1
Cursors : Disposed : The number of disposed cursors. : 13246
Clients : Active : The number of active clients. : 1
Clients : Disposed : The number of disposed clients. : 0
Streams : Active : The number of active streams. : 1
Streams : Disposed : The number of disposed streams. : 0
Streams : Egress Bytes : The number of bytes sent. : 794931
Streams : Ingress Bytes : The number of bytes received. : 589694
Streams : N Socket Timeouts : The number of socket timeouts. : 0
Client Pools : Active : The number of active client pools. : 1
Client Pools : Disposed : The number of disposed client pools. : 0
Protocol : Ingress Errors : The number of protocol errors on ingress. : 0
Auth : Failures : The number of failed authentication requests. : 0
Auth : Success : The number of successful authentication requests. : 0
Submitting a Bug Report
Think you've found a bug? Want to see a new feature in the MongoDB C driver? Please open a case in our
issue management tool, JIRA:
• Create an account and login.
• Navigate to the CDRIVER project.
• Click Create Issue - Please provide as much information as possible about the issue type and how to
reproduce it.
Bug reports in JIRA for all driver projects (i.e. CDRIVER, CSHARP, JAVA) and the Core Server (i.e.
SERVER) project are public.
Guides
Configuring TLS
Configuration with URI options
Enable TLS by including tls=true in the URI.
mongoc_uri_t *uri = mongoc_uri_new ("mongodb://localhost:27017/");
mongoc_uri_set_option_as_bool (uri, MONGOC_URI_TLS, true);
mongoc_client_t *client = mongoc_client_new_from_uri (uri);
The following URI options may be used to further configure TLS:
┌─────────────────────────────────────────────────┬──────────────────────────────────────┬────────────────────────────────────────┐
├─────────────────────────────────────────────────┼──────────────────────────────────────┼────────────────────────────────────────┤
├─────────────────────────────────────────────────┼──────────────────────────────────────┼────────────────────────────────────────┤
├─────────────────────────────────────────────────┼──────────────────────────────────────┼────────────────────────────────────────┤
├─────────────────────────────────────────────────┼──────────────────────────────────────┼────────────────────────────────────────┤
├─────────────────────────────────────────────────┼──────────────────────────────────────┼────────────────────────────────────────┤
├─────────────────────────────────────────────────┼──────────────────────────────────────┼────────────────────────────────────────┤
├─────────────────────────────────────────────────┼──────────────────────────────────────┼────────────────────────────────────────┤
├─────────────────────────────────────────────────┼──────────────────────────────────────┼────────────────────────────────────────┤
├─────────────────────────────────────────────────┼──────────────────────────────────────┼────────────────────────────────────────┤
└─────────────────────────────────────────────────┴──────────────────────────────────────┴────────────────────────────────────────┘
Configuration with mongoc_ssl_opt_t
Alternatively, the mongoc_ssl_opt_t struct may be used to configure TLS with mongoc_client_set_ssl_opts()
or mongoc_client_pool_set_ssl_opts(). Most of the configurable options can be set using the Connection
String URI.
────────────────────────────────────────────────────────────
mongoc_ssl_opt_t key URI key
────────────────────────────────────────────────────────────
pem_file tlsClientCertificateKeyFile
────────────────────────────────────────────────────────────
pem_pwd tlsClientCertificateKeyPassword
────────────────────────────────────────────────────────────
ca_file tlsCAFile
────────────────────────────────────────────────────────────
weak_cert_validation tlsAllowInvalidCertificates
────────────────────────────────────────────────────────────
allow_invalid_hostname tlsAllowInvalidHostnames
┌────────────────────────┬─────────────────────────────────┐
│ │ │
--
AUTHOR
MongoDB, Inc
COPYRIGHT
2017-present, MongoDB, Inc
1.21.0 Feb 09, 2022 MONGOC_REFERENCE(3)