MONGOC_REFERENCE(3)

πŸ’– MONGOC_REFERENCE(3) β€” libmongoc πŸ’–

okay so bestie, this is the manual page for libmongoc, and it is literally the group chat for the MongoDB C Driver API. no cap.

✨ LIBMONGOC - API ✨

A Cross Platform MongoDB Client Library for C

This site documents the API. For tutorials, guides, and explainers, see MongoDB C Driver.

🌱 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's giving β€œlow-level but make it useful” πŸ’…

It depends on libbson to generate and parse BSON documents, the native data format of MongoDB. bson is the whole vibe, fr fr.

πŸ—‚οΈ API Reference πŸ—‚οΈ

🧼 Initialization and cleanup 🧼

πŸŽ€ Synopsis πŸŽ€

Initialize the MongoDB C Driver by calling mongoc_init() exactly once at the beginning of your program. It is responsible for initializing global state such as process counters, SSL, and threading primitives. like, it sets the whole stage, okay? ✨

Exception to this is mongoc_log_set_handler(), which should be called before mongoc_init() or some log traces would not use your log handling function. See Custom Log Handlers for a detailed example.

Call mongoc_cleanup() exactly once at the end of your program to release all memory and other resources allocated by the driver. You must not call any other MongoDB C Driver functions after mongoc_cleanup(). Note that mongoc_init() does not reinitialize the driver after mongoc_cleanup(). that's a one-way exit, bestie πŸšͺ

Changed in version 2.0.0: Versions prior to 2.0.0 supported a non-portable automatic initialization and cleanup with the CMake option ENABLE_AUTOMATIC_INIT_AND_CLEANUP. This was removed in 2.0.0. Ensure your application call mongoc_init() and mongoc_cleanup().

πŸ“ Logging πŸ“

The MongoDB C driver has two different types of logging available:

  • The original mongoc_log facility supports freeform string messages that originate from the driver itself or from application code. This has been retroactively termed β€œunstructured logging”.
  • A new mongoc_structured_log facility reports messages from the driver itself using a BSON format defined across driver implementations by the MongoDB Logging Specification.

These two systems are configured and used independently. they do not share a locker, periodt.

🧸 Unstructured Logging 🧸

This is the original logging facility that supports freeform string messages originating from the driver itself or from application code. This has been retroactively termed β€œunstructured logging”. See Structured Logging for the newer standardized logging facility.

typedef enum {
   MONGOC_LOG_LEVEL_ERROR,
   MONGOC_LOG_LEVEL_CRITICAL,
   MONGOC_LOG_LEVEL_WARNING,
   MONGOC_LOG_LEVEL_MESSAGE,
   MONGOC_LOG_LEVEL_INFO,
   MONGOC_LOG_LEVEL_DEBUG,
   MONGOC_LOG_LEVEL_TRACE,
} mongoc_log_level_t;

#define MONGOC_ERROR(...)
#define MONGOC_CRITICAL(...)
#define MONGOC_WARNING(...)
#define MONGOC_MESSAGE(...)
#define MONGOC_INFO(...)
#define MONGOC_DEBUG(...)

typedef void (*mongoc_log_func_t) (mongoc_log_level_t log_level,
                                   const char *log_domain,
                                   const char *message,
                                   void *user_data);

void
mongoc_log_set_handler (mongoc_log_func_t log_func, void *user_data);
void
mongoc_log (mongoc_log_level_t log_level,
            const char *log_domain,
            const char *format,
            ...);
const char *
mongoc_log_level_str (mongoc_log_level_t log_level);
void
mongoc_log_default_handler (mongoc_log_level_t log_level,
                            const char *log_domain,
                            const char *message,
                            void *user_data);
void
mongoc_log_trace_enable (void);
void
mongoc_log_trace_disable (void);

This abstraction can be used for logging in your application, or you can integrate the driver with an existing logging system. very β€œplug it into whatever you already have” energy 🫢

πŸͺ„ Macros πŸͺ„

To make logging a little less painful, various helper macros are provided. See the following example.

#undef MONGOC_LOG_DOMAIN
#define MONGOC_LOG_DOMAIN "my-custom-domain"

MONGOC_WARNING ("An error occurred: %s", strerror (errno));

πŸŽ›οΈ Custom Log Handlers πŸŽ›οΈ

The default log handler prints a timestamp and the log message to stdout, or to stderr for warnings, critical messages, and errors. You can override the handler with mongoc_log_set_handler(). Your handler function is called in a mutex for thread safety. safety first, bestie πŸ”’

For example, you could register a custom handler to suppress messages at INFO level and below:

void
my_logger (mongoc_log_level_t log_level,
           const char *log_domain,
           const char *message,
           void *user_data)
{
   /* smaller values are more important */
   if (log_level < MONGOC_LOG_LEVEL_INFO) {
      mongoc_log_default_handler (log_level, log_domain, message, user_data);
   }
}

int
main (int argc, char *argv[])
{
   mongoc_log_set_handler (my_logger, NULL);
   mongoc_init ();

   /* ... your code ...  */

   mongoc_cleanup ();
   return 0;
}

Note that in the example above mongoc_log_set_handler() is called before mongoc_init(). Otherwise, some log traces could not be processed by the log handler.

To restore the default handler:

mongoc_log_set_handler (mongoc_log_default_handler, NULL);

πŸ”‡ Disable logging πŸ”‡

To disable all logging, including warnings, critical messages and errors, provide an empty log handler:

mongoc_log_set_handler (NULL, NULL);

πŸ” Tracing πŸ”

If compiling your own copy of the MongoDB C driver, consider configuring with -DENABLE_TRACING=ON to enable function tracing and hex dumps of network packets to STDERR and STDOUT during development and debugging. it's giving β€œx-ray vision for the driver” πŸ”₯

This is especially useful when debugging what may be going on internally in the driver.

Trace messages can be enabled and disabled by calling mongoc_log_trace_enable() and mongoc_log_trace_disable()

NOTE: Compiling the driver with -DENABLE_TRACING=ON will affect its performance. Disabling tracing with mongoc_log_trace_disable() significantly reduces the overhead, but cannot remove it completely.

🧬 Structured Logging 🧬

This document describes a newer β€œstructured” logging facility which reports messages from the driver itself using a BSON format defined across driver implementations by the MongoDB Logging Specification. See Unstructured Logging for the original freeform logging facility.

These two systems are configured and used independently.

Unstructured logging is global to the entire process, but structured logging is configured separately for each mongoc_client_t or mongoc_client_pool_t. See mongoc_client_set_structured_log_opts() and mongoc_client_pool_set_structured_log_opts(). per-client customization is the main character here πŸ‘‘

βš™οΈ Options βš™οΈ

Structured log settings are tracked explicitly by a mongoc_structured_log_opts_t instance.

Like other drivers supporting structured logging, we take default settings from environment variables and offer additional optional programmatic configuration. Environment variables are captured during mongoc_structured_log_opts_new(), refer there for a full list of the supported variables.

Normally environment variables provide defaults that can be overridden programmatically. To request the opposite behavior, where your programmatic defaults can be overridden by the environment, see mongoc_structured_log_opts_set_max_levels_from_env().

Structured log messages may be filtered in arbitrary ways by the handler, but as both a performance optimization and a convenience, a built-in filter limits the maximum log level of reported messages with a per-component setting.

🧱 mongoc_structured_log_opts_t 🧱

πŸŽ€ Synopsis πŸŽ€

typedef struct mongoc_structured_log_opts_t mongoc_structured_log_opts_t;

mongoc_structured_log_opts_t is an opaque type that contains options for the structured logging subsystem: per-component log levels, a maximum logged document length, and a handler function.

Create a mongoc_structured_log_opts_t with mongoc_structured_log_opts_new(), set options and a callback on it, then pass it to mongoc_client_set_structured_log_opts() or mongoc_client_pool_set_structured_log_opts(). Must be destroyed by calling mongoc_structured_log_opts_destroy(). don't ghost your options struct, bestie 😭

πŸ› οΈ Functions πŸ› οΈ

🌟 mongoc_structured_log_opts_new() 🌟

πŸŽ€ Synopsis πŸŽ€

mongoc_structured_log_opts_t *
mongoc_structured_log_opts_new (void);

Creates a new mongoc_structured_log_opts_t, filled with defaults captured from the current environment.

Sets a default log handler which would write a text representation of each log message to stderr, stdout, or another file configurable using MONGODB_LOG_PATH. This setting has no effect if the default handler is replaced using mongoc_structured_log_opts_set_handler().

Environment variable errors are non-fatal, and result in one-time warnings delivered as an unstructured log.

Per-component maximum levels are initialized equivalently to:

mongoc_structured_log_opts_set_max_level_for_all_components(opts, MONGOC_STRUCTURED_LOG_LEVEL_WARNING);
mongoc_structured_log_opts_set_max_levels_from_env(opts);

🌍 Environment Variables 🌍

This is a full list of the captured environment variables.

  • MONGODB_LOG_MAX_DOCUMENT_LENGTH: Maximum length for JSON-serialized documents that appear within a log message. It may be a number, in bytes, or unlimited (case insensitive) to choose an implementation-specific value near the maximum representable length. By default, the limit is 1000 bytes. This limit affects interior documents like commands and replies, not the total length of a structured log message.
  • MONGODB_LOG_PATH: A file path or one of the special strings stderr or stdout (case insensitive) specifying the destination for structured logs seen by the default handler. By default, it writes to stderr. This path will be captured during mongoc_structured_log_opts_new(), but it will not immediately be opened. If the file can't be opened, a warning is then written to the unstructured log and the handler writes structured logs to stderr instead.
⚠️ WARNING: okay so if you give MONGODB_LOG_PATH an actual file path, every single log instance (that's one stand-alone client or one pool, each one) opens that file separately for append. The results are operating system specific, babe. On UNIX-like platforms the output of each instance gets interleaved β€” in most cases without splitting up individual log messages. But notably on Windows? The first instance opens the file in exclusive mode and every instance after it just fails, falling back on the default of stderr. So if your app rocks multiple processes or multiple client pools, you're gonna want to supply a log handler that annotates each message with which log instance it came from. iykyk πŸ’…
  • MONGODB_LOG_COMMAND β€” a log level name, set as the maximum for MONGOC_STRUCTURED_LOG_COMPONENT_COMMAND.
  • MONGODB_LOG_TOPOLOGY β€” a log level name, set as the maximum for MONGOC_STRUCTURED_LOG_COMPONENT_TOPOLOGY.
  • MONGODB_LOG_SERVER_SELECTION β€” a log level name, set as the maximum for MONGOC_STRUCTURED_LOG_COMPONENT_SERVER_SELECTION.
  • MONGODB_LOG_CONNECTION β€” a log level name, set as the maximum for MONGOC_STRUCTURED_LOG_COMPONENT_CONNECTION.
  • MONGODB_LOG_ALL β€” a log level name that gets applied to all components not otherwise specified.

Heads up bestie: log level names are always case insensitive. Here's the full list of recognized names, aliases included ✨:

  • emergency, off
  • alert
  • critical
  • error
  • warning, warn
  • notice
  • informational, info
  • debug
  • trace

Returns

A newly allocated mongoc_structured_log_opts_t. πŸŽ€


mongoc_structured_log_opts_destroy()

Synopsis

void
mongoc_structured_log_opts_destroy (mongoc_structured_log_opts_t *opts);

Parameters

  • opts β€” pointer to a mongoc_structured_log_opts_t that you allocated with mongoc_structured_log_opts_new(), or NULL.

Description

This one frees every resource tied to a mongoc_structured_log_opts_t. And if opts is NULL? It simply does nothing. No drama, no crash. 🫢


mongoc_structured_log_opts_set_handler()

Synopsis

void
mongoc_structured_log_opts_set_handler (mongoc_structured_log_opts_t *opts,
                                        mongoc_structured_log_func_t log_func,
                                        void *user_data);

Sets the function that gets called to handle structured log messages, as a mongoc_structured_log_func_t. Basically you're picking who answers the phone when a log shows up πŸ“ž

Your callback gets a mongoc_structured_log_entry_t, which is the handle for pulling extra info about the log message. But listen: that entry pointer is only valid during a callback, because it's a low-cost reference to temporary data. Do not go stashing it for later, bestie, it will not slay.

Structured log handlers must be thread-safe if they're gonna be used with mongoc_client_pool_t. And handlers must avoid unbounded recursion β€” the preferred way being to avoid using any libmongoc client or pool that uses the same handler. Recursive log girlies, this means you πŸ™ˆ

This function always replaces the default log handler from mongoc_structured_log_opts_new(), if it was still set. And if log_func is set to NULL, structured logging gets disabled entirely. Periodt.

Parameters

  • opts β€” structured log options, allocated with mongoc_structured_log_opts_new().
  • log_func β€” the handler you're installing, a mongoc_structured_log_func_t, or NULL to disable structured logging.
  • user_data β€” optional user data, passed on through to your handler.
SEE ALSO: Structured Logging

mongoc_structured_log_opts_set_max_level_for_component()

Synopsis

bool
mongoc_structured_log_opts_set_max_level_for_component (mongoc_structured_log_opts_t *opts,
                                                        mongoc_structured_log_component_t component,
                                                        mongoc_structured_log_level_t level);

Sets the maximum log level, per component. Only log messages at or below this severity level get passed to mongoc_structured_log_func_t. It's giving bouncer at the club 🌈

By default, each component's log level may come from environment variables β€” see mongoc_structured_log_opts_set_max_levels_from_env().

Parameters

  • opts β€” structured log options, allocated with mongoc_structured_log_opts_new().
  • component β€” the component you're setting a max log level for, as a mongoc_structured_log_component_t.
  • level β€” the new max log level for this component, as a mongoc_structured_log_level_t.

Returns

Returns true on success, or false if the parameters you supplied were incorrect. 🧚

SEE ALSO: Structured Logging

mongoc_structured_log_opts_set_max_level_for_all_components()

Synopsis

bool
mongoc_structured_log_opts_set_max_level_for_all_components (mongoc_structured_log_opts_t *opts,
                                                             mongoc_structured_log_level_t level);

Sets every per-component maximum log level to the same value. Only log messages at or below this severity level get passed to mongoc_structured_log_func_t. And the iconic part: this is effective even for logging components not known at compile-time. One level to rule them all πŸ‘‘

Parameters

  • opts β€” structured log options, allocated with mongoc_structured_log_opts_new().
  • level β€” the max log level for all components, as a mongoc_structured_log_level_t.

Returns

Returns true on success, or false if the supplied parameters were incorrect.

SEE ALSO: Structured Logging

mongoc_structured_log_opts_set_max_levels_from_env()

Synopsis

bool
mongoc_structured_log_opts_set_max_levels_from_env (mongoc_structured_log_opts_t *opts);

Sets any maximum log levels that were requested by environment variables: MONGODB_LOG_ALL for all components, followed by the per-component log levels MONGODB_LOG_COMMAND, MONGODB_LOG_CONNECTION, MONGODB_LOG_TOPOLOGY, and MONGODB_LOG_SERVER_SELECTION. Order matters, bestie, that's the whole plot ✨

It expects the value to be recognizable by mongoc_structured_log_get_named_level(). Parse errors may cause a warning message, delivered via unstructured logging. (Side quest warning, basically.)

Component levels with no valid environment variable setting get left unmodified. Untouched. Cherished. πŸ’–

This happens automatically when mongoc_structured_log_opts_new() establishes defaults. Any subsequent programmatic changes to the mongoc_structured_log_opts_t will override the environment variable settings. But for apps that want the opposite vibe β€” environment variables overriding programmatic settings β€” you can call mongoc_structured_log_opts_set_max_levels_from_env() after calling mongoc_structured_log_opts_set_max_level_for_component() and mongoc_structured_log_opts_set_max_level_for_all_components(). That processes the environment a second time, letting it override your customized defaults. Round two, fight πŸ₯Š

Returns

Returns true on success. If warnings are encountered in the environment, returns false and may log additional information to the unstructured logging facility. And note β€” by design β€” these errors are by default non-fatal. When mongoc_structured_log_opts_new() internally calls this function, it just ignores the return value. Chill of it.

SEE ALSO: Structured Logging

mongoc_structured_log_opts_get_max_level_for_component()

Synopsis

mongoc_structured_log_level_t
mongoc_structured_log_opts_get_max_level_for_component (const mongoc_structured_log_opts_t *opts,
                                                        mongoc_structured_log_component_t component);

Parameters

  • opts β€” structured log options, allocated with mongoc_structured_log_opts_new().
  • component β€” log component, as a mongoc_structured_log_component_t.

Returns

Returns the configured maximum log level for one specific component, as a mongoc_structured_log_level_t. That could be the last value set with mongoc_structured_log_opts_set_max_level_for_component() or mongoc_structured_log_opts_set_max_level_for_all_components(), or it could be the default that came from environment variables. And if you hand it an invalid or unknown component enum? It returns the lowest log level. Lowkey dramatic but fair πŸ’€

SEE ALSO: Structured Logging

mongoc_structured_log_opts_set_max_document_length()

Synopsis

bool
mongoc_structured_log_opts_set_max_document_length (mongoc_structured_log_opts_t *opts,
                                                    size_t max_document_length);

Sets a maximum length for BSON documents that show up serialized in JSON form as part of a structured log message. Snip snip, bestie βœ‚οΈ

Serialized JSON gets truncated at this limit, interpreted as a count of UTF-8 encoded bytes. Truncation is indicated with a ... suffix β€” and the length of that suffix is not included in the max document length, okay? Also, if truncating at the exact indicated length would split a valid UTF-8 sequence, we instead truncate the document earlier, at the nearest boundary between code points. We do not split characters in this house πŸ’…

Parameters

  • opts β€” structured log options, allocated with mongoc_structured_log_opts_new().
  • max_document_length β€” maximum length for each embedded JSON document, in bytes, not including an ellipsis (...) added to indicate truncation. Values near or above INT_MAX will be rejected.

Returns

Returns true on success, or false if the maximum length you supplied is too large.

SEE ALSO: Structured Logging, mongoc_structured_log_opts_set_max_document_length_from_env()

mongoc_structured_log_opts_set_max_document_length_from_env()

Synopsis

bool
mongoc_structured_log_opts_set_max_document_length_from_env (mongoc_structured_log_opts_t *opts);

Sets a maximum document length from the MONGODB_LOG_MAX_DOCUMENT_LENGTH environment variable, if a valid setting is found. (See mongoc_structured_log_opts_new() for the rundown on supported environment variable formats πŸ“‹)

Parse errors may cause a warning message, delivered via unstructured logging.

This happens automatically when mongoc_structured_log_opts_new() establishes defaults. Any subsequent programmatic modifications to the mongoc_structured_log_opts_t will override the environment variable settings. For applications that desire the opposite behavior β€” environment variables overriding programmatic settings, iykyk β€” they may call mongoc_structured_log_opts_set_max_document_length_from_env() after calling mongoc_structured_log_opts_set_max_document_length(). That processes the environment a second time, allowing it to override customized defaults. Second pass, better vibes 🌸

Returns

Returns true on success: either a valid environment setting was found, or the value is unset and opts will not be modified. If warnings are encountered in the environment, returns false and may log additional information to the unstructured logging facility. Note that, by design, these errors are by default non-fatal. When mongoc_structured_log_opts_new() internally calls this function, it ignores the return value.

SEE ALSO: Structured Logging

mongoc_structured_log_opts_get_max_document_length()

Synopsis

size_t
mongoc_structured_log_opts_get_max_document_length (const mongoc_structured_log_opts_t *opts);

Parameters

  • opts: Structured log options, allocated with mongoc_structured_log_opts_new().

Returns

Returns the current maximum document length that's set in opts, as a size_t. Just a lil peek at the setting, very low-key, very demure. πŸ’…

SEE ALSO: Structured Logging

SEE ALSO: Structured Logging

yes bestie it literally says it twice 😭 that's just how the page is, we don't question the classics πŸ’€

🎚️ Levels and Components

Log levels and components are defined as the mongoc_structured_log_level_t and mongoc_structured_log_component_t enumerations. You get utility functions to convert between these values and their standard string representations. Oh and β€” the string values are case-insensitive, so you can be as chaotic with your capitalisation as you want. ✨

typedef enum {
  MONGOC_STRUCTURED_LOG_LEVEL_EMERGENCY = 0,  // "Emergency" ("off" also accepted)
  MONGOC_STRUCTURED_LOG_LEVEL_ALERT = 1,      // "Alert"
  MONGOC_STRUCTURED_LOG_LEVEL_CRITICAL = 2,   // "Critical"
  MONGOC_STRUCTURED_LOG_LEVEL_ERROR = 3,      // "Error"
  MONGOC_STRUCTURED_LOG_LEVEL_WARNING = 4,    // "Warning" ("warn" also accepted)
  MONGOC_STRUCTURED_LOG_LEVEL_NOTICE = 5,     // "Notice"
  MONGOC_STRUCTURED_LOG_LEVEL_INFO = 6,       // "Informational" ("info" also accepted)
  MONGOC_STRUCTURED_LOG_LEVEL_DEBUG = 7,      // "Debug"
  MONGOC_STRUCTURED_LOG_LEVEL_TRACE = 8,      // "Trace"
} mongoc_structured_log_level_t;

typedef enum {
  MONGOC_STRUCTURED_LOG_COMPONENT_COMMAND = 0,           // "command"
  MONGOC_STRUCTURED_LOG_COMPONENT_TOPOLOGY = 1,          // "topology"
  MONGOC_STRUCTURED_LOG_COMPONENT_SERVER_SELECTION = 2,  // "serverSelection"
  MONGOC_STRUCTURED_LOG_COMPONENT_CONNECTION = 3,        // "connection"
} mongoc_structured_log_component_t;

mongoc_structured_log_level_t

Synopsis

typedef enum {
   MONGOC_STRUCTURED_LOG_LEVEL_EMERGENCY = 0,
   MONGOC_STRUCTURED_LOG_LEVEL_ALERT = 1,
   MONGOC_STRUCTURED_LOG_LEVEL_CRITICAL = 2,
   MONGOC_STRUCTURED_LOG_LEVEL_ERROR = 3,
   MONGOC_STRUCTURED_LOG_LEVEL_WARNING = 4,
   MONGOC_STRUCTURED_LOG_LEVEL_NOTICE = 5,
   MONGOC_STRUCTURED_LOG_LEVEL_INFO = 6,
   MONGOC_STRUCTURED_LOG_LEVEL_DEBUG = 7,
   MONGOC_STRUCTURED_LOG_LEVEL_TRACE = 8,
} mongoc_structured_log_level_t;

mongoc_structured_log_level_t enumerates all the available log levels you can use with structured logging. Emergency through Trace, the whole alphabet of "how much do you want to know" 🌈

Functions 🫢

mongoc_structured_log_get_level_name()

Synopsis

const char *
mongoc_structured_log_get_level_name (mongoc_structured_log_level_t level);

Parameters

  • level: Log level as a mongoc_structured_log_level_t.

Returns

If the level is known, it gives you back a pointer to a constant string β€” and listen, do not free it, it's not yours like that 🚫. If the level has no known name, it returns NULL.

SEE ALSO: Structured Logging

mongoc_structured_log_get_named_level()

Synopsis

bool
mongoc_structured_log_get_named_level (const char *name, mongoc_structured_log_level_t *out);

Look up a log level by name. Case insensitive, so go off with your INFO / info / InFo era πŸ’…

Parameters

  • name: A name to look up as a log level.
  • out: On success, the corresponding mongoc_structured_log_level_t is written here.

Returns

If the level name is known, it returns true and writes the level enum to *out. If the level name is not known, it returns false and does not write *out. Consistency queen πŸ‘‘

SEE ALSO: Structured Logging

SEE ALSO: Structured Logging

mongoc_structured_log_component_t

Synopsis

typedef enum {
   MONGOC_STRUCTURED_LOG_COMPONENT_COMMAND = 0,
   MONGOC_STRUCTURED_LOG_COMPONENT_TOPOLOGY = 1,
   MONGOC_STRUCTURED_LOG_COMPONENT_SERVER_SELECTION = 2,
   MONGOC_STRUCTURED_LOG_COMPONENT_CONNECTION = 3,
} mongoc_structured_log_component_t;

mongoc_structured_log_component_t enumerates the structured logging components. Here's the important part, bestie, read it twice: applications should never rely on having an exhaustive list of all log components. Like, ever. Instead, use mongoc_structured_log_opts_set_max_level_for_all_components() to set a default level if you need one. Future-proofing is the main character here ✨

Functions 🫢

mongoc_structured_log_get_component_name()

Synopsis

const char *
mongoc_structured_log_get_component_name (mongoc_structured_log_component_t component);

Parameters

  • component: Log component as a mongoc_structured_log_component_t.

Returns

If the component is known, returns a pointer to a constant string that should not be freed. If the component has no known name, returns NULL.

SEE ALSO: Structured Logging

mongoc_structured_log_get_named_component()

Synopsis

bool
mongoc_structured_log_get_named_component (const char *name, mongoc_structured_log_component_t *out);

Look up a component by name. Case insensitive, naturally πŸ’…

Parameters

  • name: A name to look up as a log component.
  • out: On success, the corresponding mongoc_structured_log_component_t is written here.

Returns

If the component name is known, it returns true and writes the component enum to *out. If the component name is not known, it returns false and does not write *out.

SEE ALSO: Structured Logging

SEE ALSO: Structured Logging

SEE ALSO:

  • mongoc_structured_log_get_level_name
  • mongoc_structured_log_get_named_level
  • mongoc_structured_log_get_component_name
  • mongoc_structured_log_get_named_component

πŸ“¬ Log Handlers

Each mongoc_client_pool_t or standalone mongoc_client_t has its own instance of the structured logging subsystem, with its own settings and handler. Independent icon behaviour, we love to see it πŸ’–

When you're using a mongoc_client_pool_t, all the pooled clients share one common logging instance. Which means: handlers must be thread-safe. No exceptions, no vibes-based threading 🧡

The handler gets called for each log entry with a level no greater than its component's maximum. A mongoc_structured_log_entry_t pointer gives you access to further details β€” but only during the handler. Blink and it's gone 😭

Handlers must take care not to re-enter libmongoc with the same mongoc_client_t or mongoc_client_pool_t that the handler has been called by. That's the one rule, don't loop back in on yourself πŸ”πŸ’€

mongoc_structured_log_func_t

Synopsis

typedef void (*mongoc_structured_log_func_t)
(const mongoc_structured_log_entry_t *entry, void *user_data);

Callback function for mongoc_structured_log_opts_set_handler(). Structured log handlers must be thread-safe if they're going to be used with mongoc_client_pool_t. Handlers must also avoid unbounded recursion β€” preferably by avoiding the use of any libmongoc client or pool that uses the same handler. Basically: don't hand your handler a mirror and ask it to log itself πŸͺžπŸ’€

Parameters

  • entry: A mongoc_structured_log_entry_t pointer, only valid during the handler invocation.
  • user_data: Optional user data from mongoc_structured_log_opts_set_handler().

SEE ALSO: Structured Logging


πŸ“ Log Entries

Each log entry is represented inside the handler by a short-lived mongoc_structured_log_entry_t pointer. During the handler, that pointer lets you access the individual properties of an entry: its level, component, and message. Three little facts, all yours for the duration of one callback πŸ¦‹

The message gets assembled as a bson_t only when you explicitly ask for it with a call to mongoc_structured_log_entry_message_as_bson(). That gives you a standalone document you can keep for as long as you like β€” and which you must explicitly destroy. Your document, your responsibility, bestie 🫑

mongoc_structured_log_entry_t

Synopsis

typedef struct mongoc_structured_log_entry_t mongoc_structured_log_entry_t;

mongoc_structured_log_entry_t is an opaque structure representing the temporary state of an in-progress log entry. It can only be used during a mongoc_structured_log_func_t β€” it is not valid after the log handler returns. Use the functions below to query the individual aspects of the log entry. It's giving guest star, not series regular πŸ’«

Functions 🫢

mongoc_structured_log_entry_get_component()

Synopsis

mongoc_structured_log_component_t
mongoc_structured_log_entry_get_component (const mongoc_structured_log_entry_t *entry);

Parameters

  • entry: A mongoc_structured_log_entry_t pointer.

Returns

The mongoc_structured_log_component_t associated with this log entry.

SEE ALSO: Structured Logging

mongoc_structured_log_entry_get_level()

Synopsis

mongoc_structured_log_level_t
mongoc_structured_log_entry_get_level (const mongoc_structured_log_entry_t *entry);

Parameters

  • entry: A mongoc_structured_log_entry_t pointer.

Returns

The mongoc_structured_log_level_t associated with this log entry.

SEE ALSO: Structured Logging

mongoc_structured_log_entry_get_message_string()

Synopsis

const char *
mongoc_structured_log_entry_get_message_string (const mongoc_structured_log_entry_t *entry);

Parameters

  • entry: A mongoc_structured_log_entry_t pointer.

Returns

A string, guaranteed to be valid only during the lifetime of the structured log handler. It should not be freed or modified. Hands off, it's not a souvenir πŸš«πŸŽ€

Identical to the value of the message key in the document returned by mongoc_structured_log_entry_message_as_bson().

Heads up: this is not a complete string representation of the structured log. It's a standardized identifier for a particular log event. Like a name tag, not a whole biography 🏷️

SEE ALSO: Structured Logging

mongoc_structured_log_entry_message_as_bson()

Synopsis

bson_t *
mongoc_structured_log_entry_message_as_bson (const mongoc_structured_log_entry_t *entry);

Make a new copy, as a bson_t, of the log entry's standardized BSON representation. When possible, a log handler should avoid serializing log messages that will be discarded β€” don't do the work just to throw it in the bin πŸ—‘οΈβœ¨ Each call allocates an independent copy of the message that must be freed.

Parameters

  • entry: A mongoc_structured_log_entry_t pointer.

Returns

A new allocated bson_t that must be freed with a call to bson_destroy().

SEE ALSO: Structured Logging

SEE ALSO: Structured Logging


🌸 Example

example-structured-log.c β€” yes she's the demo, yes she ate πŸ’…

/* gcc example-structured-log.c -o example-structured-log \
 *     $(pkg-config --cflags --libs libmongoc-1.0) */

#include <mongoc/mongoc.h>

#include <pthread.h>

#include <stdio.h>
#include <stdlib.h>

static pthread_mutex_t handler_mutex;

static void
example_handler(const mongoc_structured_log_entry_t *entry, void *user_data)
{
   (void)user_data;

   mongoc_structured_log_component_t component = mongoc_structured_log_entry_get_component(entry);
   mongoc_structured_log_level_t level = mongoc_structured_log_entry_get_level(entry);
   const char *message_string = mongoc_structured_log_entry_get_message_string(entry);
/*
 * With a single-threaded mongoc_client_t, handlers will always be called
 * by the thread that owns the client. On a mongoc_client_pool_t, handlers
 * are shared by multiple threads and must be reentrant.
 *
 * Note that unstructured logging includes a global mutex in the API,
 * but structured logging allows applications to avoid lock contention
 * even when multiple threads are issuing commands simultaneously.
 *
 * Simple apps like this example can achieve thread safety by adding their
 * own global mutex. For other apps, this would be a performance bottleneck
 * and it would be more appropriate for handlers to process their log
 * messages concurrently.
 *
 * In this example, our mutex protects access to a global log counter.
 * In a real application, you may need to protect access to a shared stream
 * or queue.
 */
pthread_mutex_lock(&handler_mutex);

static unsigned log_serial_number = 0;

printf("%u. Log entry with component=%s level=%s message_string='%s'\n",
       ++log_serial_number,
       mongoc_structured_log_get_component_name(component),
       mongoc_structured_log_get_level_name(level),
       message_string);

/*
 * At this point, the handler might make additional filtering decisions
 * before asking for a bson_t. As an example, let's log the component and
 * level for all messages but only show contents for command logs.
 */
if (component == MONGOC_STRUCTURED_LOG_COMPONENT_COMMAND) {
   bson_t *message = mongoc_structured_log_entry_message_as_bson(entry);
   char *json = bson_as_relaxed_extended_json(message, NULL);
   printf("Full log message, as json: %s\n", json);
   bson_destroy(message);
   bson_free(json);
}

pthread_mutex_unlock(&handler_mutex);
}

int
main(void)
{
   const char *uri_string = "mongodb://localhost:27017";
   int result = EXIT_FAILURE;
   bson_error_t error;
   mongoc_uri_t *uri = NULL;
   mongoc_structured_log_opts_t *log_opts = NULL;
   mongoc_client_t *client = NULL;
   mongoc_client_pool_t *pool = NULL;

   /*
    * Note that structured logging only applies per-client or per-pool,
    * and it won't be used during or before mongoc_init.
    */
   mongoc_init();

   /*
    * Logging options are represented by a mongoc_structured_log_opts_t,
    * which can be copied into a mongoc_client_t or mongoc_client_pool_t
    * using mongoc_client_set_structured_log_opts() or
    * mongoc_client_pool_set_structured_log_opts(), respectively.
    *
    * Default settings are captured from the environment into
    * this structure when it's constructed.
    */
   log_opts = mongoc_structured_log_opts_new();

   /*
    * For demonstration purposes, set up a handler that receives all possible log messages.
    */
   pthread_mutex_init(&handler_mutex, NULL);
   mongoc_structured_log_opts_set_max_level_for_all_components(log_opts, MONGOC_STRUCTURED_LOG_LEVEL_TRACE);
   mongoc_structured_log_opts_set_handler(log_opts, example_handler, NULL);

   /*
    * By default libmongoc processes log options from the environment first,
    * and then allows you to apply programmatic overrides. To request the
    * opposite behavior, allowing the environment to override programmatic
    * defaults, you can ask for the environment to be re-read after setting
    * your own defaults.
    */
   mongoc_structured_log_opts_set_max_levels_from_env(log_opts);

   /*
    * Create a MongoDB URI object. This example assumes a local server.
    */
   uri = mongoc_uri_new_with_error(uri_string, &error);
   if (!uri) {
      fprintf(stderr, "URI parse error: %s\n", error.message);
      goto done;
   }

   /*
    * Create a new client pool.
    */
   pool = mongoc_client_pool_new(uri);
   if (!pool) {
      goto done;
   }

   /*
    * Set the client pool's log options.
    * This must happen only once, and only before the first mongoc_client_pool_pop.
    * There's no need to keep log_opts after this point.
    */
   mongoc_client_pool_set_structured_log_opts(pool, log_opts);

   /*
    * Check out a client, and do some work that we'll see logs from.
    * This example just sends a 'ping' command.
    */
   client = mongoc_client_pool_pop(pool);
   if (!client) {
      goto done;
   }

   bson_t *command = BCON_NEW("ping", BCON_INT32(1));
   bson_t reply;
   bool command_ret = mongoc_client_command_simple(client, "admin", command, NULL, &reply, &error);
   bson_destroy(command);
   bson_destroy(&reply);
   mongoc_client_pool_push(pool, client);
   if (!command_ret) {
      fprintf(stderr, "Command error: %s\n", error.message);
      goto done;
   }

   result = EXIT_SUCCESS;
done:
   mongoc_uri_destroy(uri);
   mongoc_structured_log_opts_destroy(log_opts);
   mongoc_client_pool_destroy(pool);
   mongoc_cleanup();
   return result;
}

πŸ¦‹ SEE ALSO πŸ¦‹

  • mongoc_structured_log_entry_get_component
  • mongoc_structured_log_entry_get_level
  • mongoc_structured_log_entry_message_as_bson

Β« libmongoc - API


πŸ’– Error Reporting πŸ’–

🌸 Description 🌸

ok so listen bestie β€” a lot of C Driver functions report errors the same way: they hand you back false or -1 and fill out a bson_error_t structure with three little gifts inside β€” an error domain, an error code, and a message. πŸŽ€

  • Use domain to figure out which subsystem actually generated the error.
  • Use code for the specific error.
  • message is a human-readable description of what went wrong. literally the driver explaining itself to you 🫢
SEE ALSO: Handling Errors in libbson.

πŸ‘‘ The error codes πŸ‘‘ (aka the vibe check table)

  • MONGOC_ERROR_CLIENT
    • MONGOC_ERROR_CLIENT_TOO_BIG β€” bestie you tried to send a message that's larger than the server's max message size. it's giving too much πŸ’€
    • MONGOC_ERROR_CLIENT_AUTHENTICATE β€” wrong credentials, or a failure while sending or receiving authentication messages.
    • MONGOC_ERROR_CLIENT_NO_ACCEPTABLE_PEER β€” you tried an TLS connection but the driver was not built with TLS. 😭 no TLS, no peer.
    • MONGOC_ERROR_CLIENT_IN_EXHAUST β€” you started iterating an exhaust cursor, then tried to begin another operation with the same mongoc_client_t. pick a lane, icon ✨
    • MONGOC_ERROR_CLIENT_SESSION_FAILURE β€” a failure related to creating or using a logical session.
  • MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG β€” bestie, you fumbled the arguments when you were initializing In-Use Encryption 😭 failure related to arguments passed when initializing In-Use Encryption, that's the whole vibe.
  • MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE β€” the encryption thing is in a bad state, plain and simple. Failure related to In-Use Encryption ✨
  • MONGOC_ERROR_CLIENT_INVALID_LOAD_BALANCER β€” you tried to connect to a MongoDB server behind a load balancer, but the server does not advertize load balanced support πŸ’€ that's it, that's the situation.
  • MONGOC_ERROR_CLIENT_NOT_READY β€” not me catching you trying to create a client without ever calling mongoc_init() first πŸ™ˆ you attempted to create a client but did not previously call mongoc_init(). Do the init. It's giving prerequisites.

  • MONGOC_ERROR_STREAM β€” the stream domain, home of connection sadness 🫢
    • MONGOC_ERROR_STREAM_NAME_RESOLUTION β€” DNS failure. That's it. The name did not resolve. πŸ’”
    • MONGOC_ERROR_STREAM_SOCKET β€” timeout communicating with server, or connection closed. One of the two, and neither is cute 😭
    • MONGOC_ERROR_STREAM_CONNECT β€” failed to connect to server. Straight up did not connect.
  • MONGOC_ERROR_PROTOCOL β€” protocol domain, aka "the server and I are not on the same page" ✨
    • MONGOC_ERROR_PROTOCOL_INVALID_REPLY β€” corrupt response from server. The reply was giving nonsense.
    • MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION β€” the server version is too old or too new to communicate with the driver πŸ”₯ like, no compatible wire version, so it's a no from both of us.
  • MONGOC_ERROR_CURSOR β€” cursor domain, my beloved chaotic child πŸ¦‹
    • MONGOC_ERROR_CURSOR_INVALID_CURSOR β€” okay so this one has range πŸ’… you passed bad arguments to mongoc_collection_find_with_opts(), or you called mongoc_cursor_next() on a completed or failed cursor, or the cursor timed out on the server. Three iconic ways to end up here.
  • MONGOC_ERROR_CHANGE_STREAM_NO_RESUME_TOKEN β€” a resume token was not returned in a document found with mongoc_change_stream_next() 😭 no token, no resume, that's the whole tragedy.
  • MONGOC_ERROR_QUERY β€” query domain time πŸŽ€
    • MONGOC_ERROR_QUERY_FAILURE β€” Error API Version 1: server error from command or query. The server error message is in message πŸ‘‘
  • MONGOC_ERROR_SERVER β€” same code name, different era, do not get it twisted ⭐
    • MONGOC_ERROR_QUERY_FAILURE β€” Error API Version 2: server error from command or query. The server error message is in message. fr fr, check message.
  • MONGOC_ERROR_SASL β€” a SASL error code. Run man sasl_errors for a list of codes 🌈 the literal value is the SASL code, iykyk.
  • MONGOC_ERROR_BSON β€” BSON domain, the document-validity police 🚨
    • MONGOC_ERROR_BSON_INVALID β€” you passed an invalid or oversized BSON document as a parameter, or the server reply was corrupt. Either way, something was not slaying πŸ’€

  • MONGOC_ERROR_NAMESPACE β†’ MONGOC_ERROR_NAMESPACE_INVALID β€” you tried to create a collection with an invalid name. like, the name was not namable. bestie the server said no 😭
  • MONGOC_ERROR_COMMAND β†’ MONGOC_ERROR_COMMAND_INVALID_ARG β€” so many functions set this error code when you pass them bad parameters. print the error message for the deets, it literally tells you what's wrong πŸ’…

okay so the next few rows leave the domain column blank β€” that's just the table being lazy, it means the domain is still MONGOC_ERROR_COMMAND carrying over from above 🫢

  • MONGOC_ERROR_COMMAND β†’ MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION β€” you tried to use a command option the server does not support. wrong era of server, girly πŸ’€
  • MONGOC_ERROR_COMMAND β†’ MONGOC_ERROR_DUPLICATE_KEY β€” an insert or update failed because of a duplicate _id or other unique-index violation. someone already claimed that username 😭
  • MONGOC_ERROR_COMMAND β†’ MONGOC_ERROR_MAX_TIME_MS_EXPIRED β€” the operation failed because maxTimeMS expired. ran out of clock, iconic behaviour honestly ⏰
  • MONGOC_ERROR_COMMAND β†’ MONGOC_ERROR_SERVER_SELECTION_INVALID_ID β€” the serverId option for an operation conflicts with the pinned server for that operation's client session (denoted by the sessionId option). two servers walked into a bar and could not agree πŸ¦‹
  • MONGOC_ERROR_COMMAND β€” error code from server. β€” Error API Version 1: server error from a command. the server error message lives in message ✨
  • MONGOC_ERROR_SERVER β€” error code from server. β€” Error API Version 2: server error from a command. the server error message lives in message ✨ (yes it's the same vibe, different API version, that's the whole point πŸŽ€)

  • MONGOC_ERROR_COLLECTION β†’ MONGOC_ERROR_COLLECTION_INSERT_FAILED, MONGOC_ERROR_COLLECTION_UPDATE_FAILED, MONGOC_ERROR_COLLECTION_DELETE_FAILED β€” invalid or empty input to mongoc_collection_insert_one(), mongoc_collection_insert_many(), mongoc_collection_update_one(), mongoc_collection_update_many(), mongoc_collection_replace_one(), mongoc_collection_delete_one(), or mongoc_collection_delete_many() πŸ™ˆ
  • MONGOC_ERROR_COLLECTION β€” error code from server. β€” Error API Version 1: server error from mongoc_collection_insert_one(), mongoc_collection_insert_many(), mongoc_collection_update_one(), mongoc_collection_update_many(), mongoc_collection_replace_one(),
  • MONGOC_ERROR_SERVER β€” error code from server. β€” Error API Version 2: server error from mongoc_collection_insert_one(), mongoc_collection_insert_many(), mongoc_collection_update_one(), mongoc_collection_update_many(), mongoc_collection_replace_one(),
ngl those last two lists trail off exactly like that in the original table β€” that's the whole row, not me getting distracted mid-sentence πŸ’€

  • MONGOC_ERROR_GRIDFS β†’ MONGOC_ERROR_GRIDFS_CHUNK_MISSING β€” the GridFS file is missing a document in its chunks collection. girl where did the chunk go 😭

and again, blank domain cell = still MONGOC_ERROR_GRIDFS for these two πŸ‘‡

  • MONGOC_ERROR_GRIDFS β†’ MONGOC_ERROR_GRIDFS_CORRUPT β€” a data inconsistency was detected in GridFS. something is Not Right in there πŸ’€
  • MONGOC_ERROR_GRIDFS β†’ MONGOC_ERROR_GRIDFS_INVALID_FILENAME β€” you passed a NULL filename to mongoc_gridfs_remove_by_filename(). can't delete a file with no name bestie, that's not a thing πŸŽ€
  • MONGOC_ERROR_GRIDFS_PROTOCOL_ERROR β€” bestie, this one means you called mongoc_gridfs_file_set_id() after mongoc_gridfs_file_save(), or you tried to write on a closed GridFS stream. order matters, okay?? 😭
  • MONGOC_ERROR_GRIDFS_BUCKET_FILE_NOT_FOUND β€” a GridFS file is missing from the files collection. it's just… not there. gone. πŸ’€
  • MONGOC_ERROR_GRIDFS_BUCKET_STREAM β€” an error occurred on a stream created from a GridFS operation like mongoc_gridfs_bucket_upload_from_stream(). stream said no 🫢

  • MONGOC_ERROR_SCRAM 🌸
    • MONGOC_ERROR_SCRAM_PROTOCOL_ERROR β€” failure in SCRAM-SHA-1 or SCRAM-SHA-256 authentication. the auth handshake did not slay, ngl
  • MONGOC_ERROR_SERVER_SELECTION πŸ”
    • MONGOC_ERROR_SERVER_SELECTION_FAILURE β€” no replica set member or mongos is available, or none of them matches your read preference, or you supplied an invalid mongoc_read_prefs_t. three ways to end up here, all of them lowkey tragic
  • MONGOC_ERROR_WRITE_CONCERN
    • the code here is literally Error code from server.
    • and the meaning: there was a write concern error or timeout from the server. the server said "hmm, no" πŸ’…
  • MONGOC_ERROR_TRANSACTION 🧚
    • MONGOC_ERROR_TRANSACTION_INVALID β€” you attempted to start a transaction when one is already in progress, or commit or abort when there is no transaction. bestie you can't start a vibe that's already started, and you can't end one that never began ✨
  • MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION πŸ”
    • the code is Error code produced by libmongocrypt.
    • and the meaning: an error occurred in the library responsible for In-Use Encryption
  • MONGOC_ERROR_AZURE ☁️
    • MONGOC_ERROR_KMS_SERVER_HTTP β€” an Azure HTTP service responded with an error status
    • MONGOC_ERROR_KMS_SERVER_BAD_JSON β€” an Azure service responded with invalid JSON data. JSON said ✨nope✨
  • MONGOC_ERROR_GCP 🌈
    • MONGOC_ERROR_KMS_SERVER_HTTP β€” a GCP HTTP service responded with an error status
    • MONGOC_ERROR_KMS_SERVER_BAD_JSON β€” a GCP service responded with invalid JSON data. same vibe, different cloud πŸŽ€

🌸 Error Labels 🌸

okay so sometimes your app literally <emphasis>has</emphasis> to make a decision based on what category of error the driver threw at you β€” but those categories don't map perfectly onto an error domain or an error code. that's the whole reason error labels exist, bestie. they're the reliable way to figure out how your app should react. no cap.

Any C Driver function that has a bson_t out-parameter named reply may include error labels in that reply, as a BSON field named "errorLabels" holding an array of strings:

{ "errorLabels": [ "TransientTransactionError" ] }

Use mongoc_error_has_label() to test whether a reply contains a specific label πŸ’…. For example code that shows error labels doing their thing in actual application logic, go peek at mongoc_client_session_start_transaction().

The following error labels are currently defined. Future versions of MongoDB may introduce new labels. πŸ‘‘

πŸŒ€ TransientTransactionError πŸŒ€

Inside a multi-document transaction, certain errors can leave the transaction in an unknown or aborted state 😭. these include write conflicts, primary stepdowns, and network errors. what should you do? abort the transaction and try the same sequence of operations again in a new transaction. that's it, that's the move. 🫢

❓ UnknownTransactionCommitResult ❓

when mongoc_client_session_commit_transaction() hits a network error or certain server errors, nobody knows whether the transaction was actually committed. genuinely unknown. πŸ™ˆ applications should attempt to commit the transaction again until:

  • the commit succeeds ✨
  • the commit fails with an error that is <emphasis>not</emphasis> labeled "UnknownTransactionCommitResult"
  • or your application just chooses to give up πŸ’€

🧚 Setting the Error API Version 🧚

ngl, the driver's error reporting started out with a design flaw: when the error domain is MONGOC_ERROR_COLLECTION, MONGOC_ERROR_QUERY, or MONGOC_ERROR_COMMAND, the error code might originate from the server or from the driver. an application can't always know where an error came from, so it literally cannot tell what the code even means. it's giving chaos.

for example: if mongoc_collection_update_one() sets the error's domain to MONGOC_ERROR_COLLECTION and its code to 24, your application has no idea whether that 24 is the generic driver error code MONGOC_ERROR_COLLECTION_UPDATE_FAILED or the specific server error code "LockTimeout". πŸŽ€

To fix this flaw while preserving backward compatibility, the C Driver 1.4 introduces "Error API Versions" 🌈:

  • Version 1 β€” the default Error API Version β€” maintains the flawed behavior.
  • Version 2 β€” adds a new error domain, MONGOC_ERROR_SERVER. in Version 2, error codes originating on the server always have error domain MONGOC_ERROR_SERVER or MONGOC_ERROR_WRITE_CONCERN. so when the driver uses Version 2, your application can always determine the origin and meaning of error codes. slay.

New applications should use Version 2, and existing applications should be updated to use Version 2 as well. periodt. πŸ‘‘

here's the full glow-up breakdown, source by source:

  • mongoc_cursor_error()
    • API Version 1: MONGOC_ERROR_QUERY
    • API Version 2: MONGOC_ERROR_SERVER
  • mongoc_client_command_with_opts(), mongoc_database_command_with_opts(), and other command functions
    • API Version 1: MONGOC_ERROR_QUERY
    • API Version 2: MONGOC_ERROR_SERVER
  • mongoc_client_get_database_names_with_opts() and other command helper functions
    • API Version 1: MONGOC_ERROR_QUERY
    • API Version 2: MONGOC_ERROR_SERVER
  • mongoc_collection_insert_one(), mongoc_collection_insert_many(), mongoc_collection_update_one(), mongoc_collection_update_many(), mongoc_collection_replace_one(), mongoc_collection_delete_one(), mongoc_collection_delete_many()
    • API Version 1: MONGOC_ERROR_COMMAND
    • API Version 2: MONGOC_ERROR_SERVER
  • mongoc_bulk_operation_execute()
    • API Version 1: MONGOC_ERROR_COMMAND
    • API Version 2: MONGOC_ERROR_SERVER
  • Write-concern timeout
    • API Version 1: MONGOC_ERROR_WRITE_CONCERN
    • API Version 2: MONGOC_ERROR_WRITE_CONCERN

(yes, that last one is the same in both versions β€” write-concern timeouts stay iconically unchanged πŸ’…βœ¨)

okay so before we get into the juicy stuff, a quick word on the Error API πŸ’œ The two Error API versions are called MONGOC_ERROR_API_VERSION_LEGACY and MONGOC_ERROR_API_VERSION_2 β€” those are your only two choices, bestie, no secret third one. You set whichever one you want with mongoc_client_set_error_api() or, if you're a pool girlie, mongoc_client_pool_set_error_api().

SEE ALSO:

  • MongoDB Server Error Codes

πŸ¦‹ Object Lifecycle

This page is literally a ✨map✨ of the order you create and destroy libmongoc's main struct types. Get the order wrong and things get ugly, so pay attention bestie 🫢

🌸 Clients and pools

Call mongoc_init() exactly once, before you call any other libmongoc function β€” like, any of them. Then call mongoc_cleanup() once before your program exits. That's the whole ritual, no cap.

If your program is using libmongoc from multiple threads, you should create a mongoc_client_pool_t with mongoc_client_pool_new(). Each thread then acquires a mongoc_client_t from the pool with mongoc_client_pool_pop(), and returns it with mongoc_client_pool_push() once that thread is done using it. To destroy the pool: first return all the clients, then call mongoc_client_pool_destroy(). In that order. Don't skip steps πŸ’…

If your program only uses libmongoc from a single thread, you can just create a mongoc_client_t directly with mongoc_client_new() or mongoc_client_new_from_uri(), and destroy it with mongoc_client_destroy(). Simple, iconic, no pool needed 🌈

You can create a mongoc_database_t or a mongoc_collection_t from a mongoc_client_t, and you can create a mongoc_cursor_t or a mongoc_bulk_operation_t from a mongoc_collection_t. It's giving very nesting-doll energy πŸͺ†

Every one of these objects must be destroyed before the client it was created from. Other than that one rule, their lifetimes are fully independent β€” do whatever, live your truth ✨

⭐ GridFS objects

So here's the chain, and yes it's a whole chain: you can create a mongoc_gridfs_t from a mongoc_client_t, create a mongoc_gridfs_file_t or a mongoc_gridfs_file_list_t from a mongoc_gridfs_t, create a mongoc_gridfs_file_t from a mongoc_gridfs_file_list_t, and create a mongoc_stream_t from a mongoc_gridfs_file_t. Obsessed with the pipeline honestly πŸ”₯

Each of these objects depends on the object it was created from. So always destroy GridFS objects in the reverse of the order they were created β€” last one made is the first one gone, periodt.

The sole exception: a mongoc_gridfs_file_t does not need to be destroyed before the mongoc_gridfs_file_list_t it was created from. That one gets a pass πŸ™ˆ


🧚 GridFS bucket objects

Create a mongoc_gridfs_bucket_t with a mongoc_database_t that's derived from a mongoc_client_t. The mongoc_database_t is independent from the mongoc_gridfs_bucket_t β€” they don't owe each other anything. But the mongoc_client_t must outlive the mongoc_gridfs_bucket_t. The client is the main character here, and it stays alive longest πŸ‘‘

A mongoc_stream_t may be created from the mongoc_gridfs_bucket_t, and in that case the mongoc_gridfs_bucket_t must outlive the mongoc_stream_t.

πŸ’œ Sessions

Start a session with mongoc_client_start_session(), use it for a sequence of operations and multi-document transactions, then free it with mongoc_client_session_destroy(). Any mongoc_cursor_t or mongoc_change_stream_t using a session must be destroyed before the session, and a session must be destroyed before the mongoc_client_t it came from. Chain of command, bestie 🫑

By default, sessions are causally consistent. If you want to turn that off: before starting a session, create a mongoc_session_opt_t with mongoc_session_opts_new(), call mongoc_session_opts_set_causal_consistency(), then free the struct with mongoc_session_opts_destroy().

⚠️ Unacknowledged writes are prohibited with sessions. Not allowed. Not a vibe. Don't do it πŸ’€

A mongoc_client_session_t must be used by only one thread at a time. And here's the sneaky part: because of session pooling, mongoc_client_start_session() may hand you back a session that's been idle for a while and is literally about to be closed after its idle timeout 😭 So use the session within one minute of acquiring it to refresh it and dodge that timeout entirely. Clock's ticking, babe ⏰

πŸ”₯ Client Side Encryption

When you're configuring a mongoc_client_t for automatic encryption via mongoc_client_enable_auto_encryption(), if a separate key vault client is set in the options (that's via mongoc_auto_encryption_opts_set_keyvault_client()), then the key vault client must outlive the encrypted client. Like, it goes first, no exceptions πŸ’…

When you're configuring a mongoc_client_pool_t for automatic encryption via mongoc_client_pool_enable_auto_encryption(), if a separate key vault client pool is set in the options (via mongoc_auto_encryption_opts_set_keyvault_client_pool()), then that key vault client pool must outlive the encrypted client pool.

And when you're creating a mongoc_client_encryption_t, the configured key vault client (set via mongoc_client_encryption_opts_set_keyvault_client()) must outlive the mongoc_client_encryption_t. Same energy, different struct πŸŽ€

πŸ“ GridFS

Real talk: the C driver includes two APIs for GridFS, and they are not the same girlie.

The older API consists of mongoc_gridfs_t and its derivatives. It contains deprecated API, it does not support read preferences, and it is not recommended in new applications. Also β€” and this is the big one β€” it does not conform to the MongoDB GridFS specification. Yeah. πŸ’€

The newer API consists of mongoc_gridfs_bucket_t and lets you upload/download through derived mongoc_stream_t objects. It does conform to the MongoDB GridFS specification. Slay ✨

There is not always a straightforward upgrade path from an application built with mongoc_gridfs_t to mongoc_gridfs_bucket_t (for example, a mongoc_gridfs_file_t provides functions to seek but a mongoc_stream_t does not 😭). But users are encouraged to upgrade when possible β€” future you will be so grateful πŸ’–


🌈 mongoc_auto_encryption_opts_t

Options for enabling automatic encryption and decryption for In-Use Encryption. That's it, that's the whole job.

Synopsis

typedef struct _mongoc_auto_encryption_opts_t mongoc_auto_encryption_opts_t;

SEE ALSO:

  • In-Use Encryption

πŸŽ€ mongoc_bulkwrite_t

Synopsis

typedef struct _mongoc_bulkwrite_t mongoc_bulkwrite_t;

Description

mongoc_bulkwrite_t provides an abstraction for submitting multiple write operations as a single batch. Group chat for writes, basically πŸ“¨

After adding all of the write operations to the mongoc_bulkwrite_t, call mongoc_bulkwrite_execute() to execute the operation.

⚠️ WARNING: It is only valid to call mongoc_bulkwrite_execute() once. The mongoc_bulkwrite_t must be destroyed afterwards. One shot, one kill, no reruns πŸ’…
πŸ“ NOTE: If you're using MongoDB server 8.0+, prefer mongoc_bulkwrite_t over mongoc_bulk_operation_t to reduce network round trips. Fewer trips = happier you πŸ¦‹ mongoc_bulkwrite_t uses the bulkWrite server command introduced in MongoDB server 8.0. The bulkWrite command supports insert, update, and delete operations in the same payload. bulkWrite supports use of multiple collection namespaces in the same payload. Iconic behaviour honestly πŸ‘‘ mongoc_bulk_operation_t uses the insert, update and delete server commands available in all current MongoDB server versions. Write operations are grouped by type (insert, update, delete) and sent in separate commands. Only one collection may be specified per bulk write.

⭐ mongoc_bulkwriteopts_t

Synopsis

typedef struct _mongoc_bulkwriteopts_t mongoc_bulkwriteopts_t;

🌸 mongoc_bulkwriteresult_t

Synopsis

typedef struct _mongoc_bulkwriteresult_t mongoc_bulkwriteresult_t;

πŸ’€ mongoc_bulkwriteexception_t

Synopsis

typedef struct _mongoc_bulkwriteexception_t mongoc_bulkwriteexception_t;

🫢 mongoc_bulkwrite_check_acknowledged_t

Synopsis

typedef struct {
   bool is_ok;           // true if no error
   bool is_acknowledged; // true if the previous call to `mongoc_bulkwrite_execute` used an acknowledged write concern
} mongoc_bulkwrite_check_acknowledged_t;

Description

mongoc_bulkwrite_check_acknowledged_t is returned by mongoc_bulkwrite_check_acknowledged().

is_ok is false if there was no previous call to mongoc_bulkwrite_execute() or if execution failed before the write concern could be determined. So like, if it's false, something went sideways β€” either you never ran it or it broke before we could even tell πŸ™ˆ

is_acknowledged is true if the previous mongoc_bulkwrite_execute() call used an acknowledged write concern.


πŸ’œ mongoc_bulkwrite_serverid_t

Synopsis

typedef struct {
   bool is_ok;        // true if no error
   uint32_t serverid; // the server ID last used in `mongoc_bulkwrite_execute`
} mongoc_bulkwrite_serverid_t;

Description

mongoc_bulkwrite_serverid_t is returned by mongoc_bulkwrite_serverid().

is_ok is false if there was no previous call to mongoc_bulkwrite_execute() or if execution failed.

serverid is the server ID that was last used in mongoc_bulkwrite_execute() πŸ’…


🧱 mongoc_bulk_operation_t β€” Bulk Write Operations 🧱

Synopsis

typedef struct _mongoc_bulk_operation_t mongoc_bulk_operation_t;

Description

Okay bestie, so mongoc_bulk_operation_t gives you an abstraction for submitting multiple write operations as a single batch. It's basically the group-chat organizer of your writes β€” one batch, one vibe. ✨

Once you've added all the write operations to your mongoc_bulk_operation_t, you call mongoc_bulk_operation_execute() to actually run it.

⚠️ WARNING: it is only valid to call mongoc_bulk_operation_execute() once. The mongoc_bulk_operation_t must be destroyed afterwards. No re-runs, no take-backs β€” one and done, periodt. 😭

SEE ALSO:

  • Bulk Write Operations
  • mongoc_bulkwrite_t
πŸ“ NOTE: if you're on MongoDB server 8.0+, prefer mongoc_bulkwrite_t over mongoc_bulk_operation_t to reduce network round trips. Fewer round trips = fewer little delays = so much better for your vibe check. πŸ”₯

So like, here's the tea on the difference:

mongoc_bulkwrite_t uses the bulkWrite server command introduced in MongoDB server 8.0. The bulkWrite command supports insert, update, and delete operations in the same payload. bulkWrite supports use of multiple collection namespaces in the same payload. Iconic, honestly.

mongoc_bulk_operation_t uses the insert, update and delete server commands available in all current MongoDB server versions. Write operations are grouped by type (insert, update, delete) and sent in separate commands. Only one collection may be specified per bulk write. Old-school but reliable 🫢


🌊 mongoc_change_stream_t 🌊

Synopsis

#include <mongoc/mongoc.h>

typedef struct _mongoc_change_stream_t mongoc_change_stream_t;

mongoc_change_stream_t is a handle to a change stream πŸ’– A collection change stream can be obtained using mongoc_collection_watch().

It is recommended to use a mongoc_change_stream_t and its functions instead of a raw aggregation with a $changeStream stage. For more information see the MongoDB Manual Entry on Change Streams. Trust the process, it's giving convenience. ✨

Example

example-collection-watch.c

#include <mongoc/mongoc.h>

int
main(void)
{
   bson_t empty = BSON_INITIALIZER;
   const bson_t *doc;
   bson_t *to_insert = BCON_NEW("x", BCON_INT32(1));
   const bson_t *err_doc;
   bson_error_t error;
   const char *uri_string;
   mongoc_uri_t *uri;
   mongoc_client_t *client;
   mongoc_collection_t *coll;
   mongoc_change_stream_t *stream;
   mongoc_write_concern_t *wc = mongoc_write_concern_new();
   bson_t opts = BSON_INITIALIZER;
   bool r;

   mongoc_init();

   uri_string = "mongodb://"
                "localhost:27017,localhost:27018,localhost:"
                "27019/db?replicaSet=rs0";

   uri = mongoc_uri_new_with_error(uri_string, &error);
   if (!uri) {
      fprintf(stderr,
              "failed to parse URI:\n"
              "error message: %s\n",
              error.message);
      return EXIT_FAILURE;
   }

   client = mongoc_client_new_from_uri(uri);
   if (!client) {
      return EXIT_FAILURE;
   }

   coll = mongoc_client_get_collection(client, "db", "coll");
   stream = mongoc_collection_watch(coll, &empty, NULL);

   mongoc_write_concern_set_wmajority(wc, 10000);
   mongoc_write_concern_append(wc, &opts);
   r = mongoc_collection_insert_one(coll, to_insert, &opts, NULL, &error);
   if (!r) {
      fprintf(stderr, "Error: %s\n", error.message);
      return EXIT_FAILURE;
   }

   while (mongoc_change_stream_next(stream, &doc)) {
      char *as_json = bson_as_relaxed_extended_json(doc, NULL);
      fprintf(stderr, "Got document: %s\n", as_json);
      bson_free(as_json);
   }

   if (mongoc_change_stream_error_document(stream, &error, &err_doc)) {
      if (!bson_empty(err_doc)) {
         fprintf(stderr, "Server Error: %s\n", bson_as_relaxed_extended_json(err_doc, NULL));
      } else {
         fprintf(stderr, "Client Error: %s\n", error.message);
      }
      return EXIT_FAILURE;
   }

   bson_destroy(to_insert);
   mongoc_write_concern_destroy(wc);
   bson_destroy(&opts);
   mongoc_change_stream_destroy(stream);
   mongoc_collection_destroy(coll);
   mongoc_uri_destroy(uri);
   mongoc_client_destroy(client);
   mongoc_cleanup();

   return EXIT_SUCCESS;
}

🎬 Starting and Resuming 🎬

All watch functions accept several options to indicate where a change stream should start returning changes from: resumeAfter, startAfter, and startAtOperationTime. Pick your starting point, bestie πŸŽ€

All changes returned by mongoc_change_stream_next() include a resume token in the _id field. MongoDB 4.2 also includes an additional resume token in each "aggregate" and "getMore" command response, which points to the end of that response's batch. The current token is automatically cached by libmongoc. In the event of an error, libmongoc attempts to recreate the change stream starting where it left off by passing the cached resume token. libmongoc only attempts to resume once, but client applications can access the cached resume token with mongoc_change_stream_get_resume_token() and use it for their own resume logic by passing it as either the resumeAfter or startAfter option. DIY queen energy πŸ‘‘

Additionally, change streams can start returning changes at an operation time by using the startAtOperationTime field. This can be the timestamp returned in the operationTime field of a command reply.

resumeAfter, startAfter, and startAtOperationTime are mutually exclusive options. Setting more than one will result in a server error. Pick one, bestie β€” the server will not be nice about it πŸ™ˆ

The following example implements custom resuming logic, persisting the resume token in a file.

example-resume.c

#include <mongoc/mongoc.h>

/* An example implementation of custom resume logic in a change stream.
 * example-resume starts a client-wide change stream and persists the resume
 * token in a file "resume-token.json". On restart, if "resume-token.json"
 * exists, the change stream starts watching after the persisted resume token.
 *
 * This behavior allows a user to exit example-resume, and restart it later
 * without missing any change events.
 */
#include <unistd.h>

static const char *RESUME_TOKEN_PATH = "resume-token.json";

static bool
_save_resume_token(const bson_t *doc)
{
   FILE *file_stream;
   bson_iter_t iter;
   bson_t resume_token_doc;
   char *as_json = NULL;
   size_t as_json_len;
   const bson_value_t *resume_token;

   if (!bson_iter_init_find(&iter, doc, "_id")) {
      fprintf(stderr, "reply does not contain operationTime.");
      return false;
   }
   resume_token = bson_iter_value(&iter);
   /* store the resume token in a document, { resumeAfter: <resume token> }
    * which we can later append easily. */
   file_stream = fopen(RESUME_TOKEN_PATH, "w+");
   if (!file_stream) {
      fprintf(stderr, "failed to open %s for writing\n", RESUME_TOKEN_PATH);
      return false;
   }
   bson_init(&resume_token_doc);
   BSON_APPEND_VALUE(&resume_token_doc, "resumeAfter", resume_token);
   as_json = bson_as_canonical_extended_json(&resume_token_doc, &as_json_len);
   bson_destroy(&resume_token_doc);
   size_t n_written = 0;
   while (n_written < as_json_len) {
      ssize_t r = fwrite((void *)(as_json + n_written), sizeof(char), as_json_len - n_written, file_stream);
      if (r == -1) {
         fprintf(stderr, "failed to write to %s\n", RESUME_TOKEN_PATH);
         bson_free(as_json);
         fclose(file_stream);
         return false;
      }
      n_written += r;
   }

   bson_free(as_json);
   fclose(file_stream);
   return true;
}

bool
_load_resume_token(bson_t *opts)
{
   bson_error_t error;
   bson_json_reader_t *reader;
   bson_t doc;

   /* if the file does not exist, skip. */
   if (-1 == access(RESUME_TOKEN_PATH, R_OK)) {
      return true;
   }
   reader = bson_json_reader_new_from_file(RESUME_TOKEN_PATH, &error);
   if (!reader) {
      fprintf(stderr, "failed to open %s for reading: %s\n", RESUME_TOKEN_PATH, error.message);
      return false;
   }

   bson_init(&doc);
   if (-1 == bson_json_reader_read(reader, &doc, &error)) {
      fprintf(stderr, "failed to read doc from %s\n", RESUME_TOKEN_PATH);
      bson_destroy(&doc);
      bson_json_reader_destroy(reader);
      return false;
   }

   printf("found cached resume token in %s, resuming change stream.\n", RESUME_TOKEN_PATH);

   bson_concat(opts, &doc);
   bson_destroy(&doc);
   bson_json_reader_destroy(reader);
   return true;
}

int
main(void)
{
   int exit_code = EXIT_FAILURE;
   const char *uri_string;
   mongoc_uri_t *uri = NULL;
   bson_error_t error;
   mongoc_client_t *client = NULL;
   bson_t pipeline = BSON_INITIALIZER;
   bson_t opts = BSON_INITIALIZER;
   mongoc_change_stream_t *stream = NULL;
   const bson_t *doc;

   const int max_time = 30; /* max amount of time, in seconds, that
                               mongoc_change_stream_next can block. */

   mongoc_init();
   uri_string = "mongodb://localhost:27017/db?replicaSet=rs0";
   uri = mongoc_uri_new_with_error(uri_string, &error);
   if (!uri) {
      fprintf(stderr,
              "failed to parse URI:\n"
              "error message: %s\n",
              error.message);
      goto cleanup;
   }

   client = mongoc_client_new_from_uri(uri);
   if (!client) {
      goto cleanup;
   }

   if (!_load_resume_token(&opts)) {
      goto cleanup;
   }
   BSON_APPEND_INT64(&opts, "maxAwaitTimeMS", max_time * 1000);

   printf("listening for changes on the client (max %d seconds).\n", max_time);
   stream = mongoc_client_watch(client, &pipeline, &opts);

   while (mongoc_change_stream_next(stream, &doc)) {
      char *as_json;

      as_json = bson_as_canonical_extended_json(doc, NULL);
      printf("change received: %s\n", as_json);
      bson_free(as_json);
      if (!_save_resume_token(doc)) {
         goto cleanup;
      }
   }

   exit_code = EXIT_SUCCESS;
          cleanup:
             mongoc_uri_destroy(uri);
             bson_destroy(&pipeline);
             bson_destroy(&opts);
             mongoc_change_stream_destroy(stream);
             mongoc_client_destroy(client);
             mongoc_cleanup();
             return exit_code;
          }

okay and that's the first example fully wrapped up β€” cleanup label ate, resources freed, exit code returned, no leaks, we love to see it πŸ’…


The next example is the one where we use startAtOperationTime to sync a change stream up with some other operation. honestly kind of iconic behavior.

example-start-at-optime.c

          /* An example of starting a change stream with startAtOperationTime. */
          #include <mongoc/mongoc.h>

          int
          main(void)
          {
             int exit_code = EXIT_FAILURE;
             const char *uri_string;
             mongoc_uri_t *uri = NULL;
             bson_error_t error;
             mongoc_client_t *client = NULL;
             mongoc_collection_t *coll = NULL;
             bson_t pipeline = BSON_INITIALIZER;
             bson_t opts = BSON_INITIALIZER;
             mongoc_change_stream_t *stream = NULL;
             bson_iter_t iter;
             const bson_t *doc;
             bson_value_t cached_operation_time = {0};
             int i;
             bool r;

             mongoc_init();
             uri_string = "mongodb://localhost:27017/db?replicaSet=rs0";
             uri = mongoc_uri_new_with_error(uri_string, &error);
             if (!uri) {
                fprintf(stderr,
                        "failed to parse URI:\n"
                        "error message: %s\n",
                        error.message);
                goto cleanup;
             }

             client = mongoc_client_new_from_uri(uri);
             if (!client) {
                goto cleanup;
             }

             /* insert five documents. */
             coll = mongoc_client_get_collection(client, "db", "coll");
             for (i = 0; i < 5; i++) {
                bson_t reply;
                bson_t *insert_cmd = BCON_NEW("insert", "coll", "documents", "[", "{", "x", BCON_INT64(i), "}", "]");

                r = mongoc_collection_write_command_with_opts(coll, insert_cmd, NULL, &reply, &error);
                bson_destroy(insert_cmd);
                if (!r) {
                   bson_destroy(&reply);
                   fprintf(stderr, "failed to insert: %s\n", error.message);
                   goto cleanup;
                }
                if (i == 0) {
                   /* cache the operation time in the first reply. */
                   if (bson_iter_init_find(&iter, &reply, "operationTime")) {
                      bson_value_copy(bson_iter_value(&iter), &cached_operation_time);
                   } else {
                      fprintf(stderr, "reply does not contain operationTime.");
                      bson_destroy(&reply);
                      goto cleanup;
                   }
                }
                bson_destroy(&reply);
             }

             /* start a change stream at the first returned operationTime. */
             BSON_APPEND_VALUE(&opts, "startAtOperationTime", &cached_operation_time);
             stream = mongoc_collection_watch(coll, &pipeline, &opts);

             /* since the change stream started at the operation time of the first
              * insert, the five inserts are returned. */
             printf("listening for changes on db.coll:\n");
             while (mongoc_change_stream_next(stream, &doc)) {
                char *as_json;

                as_json = bson_as_canonical_extended_json(doc, NULL);
                printf("change received: %s\n", as_json);
                bson_free(as_json);
             }

             exit_code = EXIT_SUCCESS;

          cleanup:
             mongoc_uri_destroy(uri);
             bson_destroy(&pipeline);
             bson_destroy(&opts);
             if (cached_operation_time.value_type) {
                bson_value_destroy(&cached_operation_time);
             }
             mongoc_change_stream_destroy(stream);
             mongoc_collection_destroy(coll);
             mongoc_client_destroy(client);
             mongoc_cleanup();
             return exit_code;
          }

like, notice the little detail where cached_operation_time only gets destroyed if cached_operation_time.value_type is set? that's the "don't destroy something we never filled in" check and it's lowkey very good hygiene 🧚


mongoc_client_encryption_t</p>

Synopsis

          typedef struct _mongoc_client_encryption_t mongoc_client_encryption_t;

so mongoc_client_encryption_t is the lil utility-functions holder for In-Use Encryption. that's its whole job bestie ✨

Thread Safety

ok so pay attention: mongoc_client_encryption_t is NOT thread-safe 🚨 and you should only ever use it in the same thread as the mongoc_client_t that got configured via mongoc_client_encryption_opts_set_keyvault_client(). no sharing, no passing it around the group chat.

Lifecycle

the key vault client β€” the one you set up with mongoc_client_encryption_opts_set_keyvault_client() β€” must outlive the mongoc_client_encryption_t. it's the responsible older sibling in this relationship, fr.

SEE ALSO:

  • mongoc_client_enable_auto_encryption()
  • mongoc_client_pool_enable_auto_encryption()
  • In-Use Encryption for libmongoc
  • The MongoDB Manual for Client-Side Field Level Encryption
  • The MongoDB Manual for Queryable Encryption

mongoc_client_encryption_datakey_opts_t

Synopsis

          typedef struct _mongoc_client_encryption_datakey_opts_t mongoc_client_encryption_datakey_opts_t;

this one is literally just for setting options when you call mongoc_client_encryption_create_datakey(). that's it. that's the whole vibe πŸŽ€

SEE ALSO:

  • mongoc_client_encryption_create_datakey()

mongoc_client_encryption_rewrap_many_datakey_result_t

Synopsis

          typedef struct _mongoc_client_encryption_rewrap_many_datakey_result_t
             mongoc_client_encryption_rewrap_many_datakey_result_t;

you use this bad boy to get at the result of mongoc_client_encryption_rewrap_many_datakey(). results girlies stay winning πŸ’…

SEE ALSO:

  • mongoc_client_encryption_rewrap_many_datakey()

mongoc_client_encryption_encrypt_opts_t

Synopsis

          typedef struct _mongoc_client_encryption_encrypt_opts_t mongoc_client_encryption_encrypt_opts_t;

options container for mongoc_client_encryption_encrypt(). simple. clean. no notes ✨

SEE ALSO:

  • mongoc_client_encryption_encrypt()

mongoc_client_encryption_encrypt_string_opts_t

Synopsis

          typedef struct _mongoc_client_encryption_encrypt_string_opts_t mongoc_client_encryption_encrypt_string_opts_t;
Changed in version 2.4.0: Renamed from the now-deprecated text API. πŸ‘€ so if you see the old text API name floating around, that's the deprecated one, don't @ it.

StringOpts specifies index options for a Queryable Encryption field supporting "string" queries. and yeah, it's used to set options for mongoc_client_encryption_encrypt().

here's the rules bestie, memorize them:

  • Case sensitive and diacritic sensitive must be set.
  • If prefix or suffix are set, substring must not be set.

SEE ALSO:

  • mongoc_client_encryption_encrypt()
  • mongoc_client_encryption_encrypt_opts_t

mongoc_client_encryption_encrypt_range_opts_t

Synopsis

          typedef struct _mongoc_client_encryption_encrypt_range_opts_t mongoc_client_encryption_encrypt_range_opts_t;
New in version 1.24.0. πŸ¦‹

RangeOpts specifies index options for a Queryable Encryption field supporting "range" queries, and it's used to set options for mongoc_client_encryption_encrypt().

the requirements, and please don't skip these:

  • The options min, max, trim factor, sparsity, and range must match the values set in the encryptedFields of the destination collection. mismatch = chaos, no cap.
  • For double and decimal128 fields, min/max/precision must all be set, or all be unset. no halfsies πŸ™ˆ

SEE ALSO:

  • mongoc_client_encryption_encrypt()
  • mongoc_client_encryption_encrypt_opts_t

mongoc_client_encryption_opts_t

Synopsis

          typedef struct _mongoc_client_encryption_opts_t mongoc_client_encryption_opts_t;

options for mongoc_client_encryption_new(). setting-the-options-for-the-thing energy, you know how it is πŸ’œ

SEE ALSO:

  • mongoc_client_encryption_new()

mongoc_client_pool_t

a connection pool for multi-threaded programs. see Connection Pooling. this is the multithreading main character πŸ‘‘

Synopsis

          typedef struct _mongoc_client_pool_t mongoc_client_pool_t

mongoc_client_pool_t is the basis for multi-threading in the MongoDB C driver. since mongoc_client_t structures are not thread-safe, you use this structure to grab a fresh mongoc_client_t for a given thread. slay.

and here's the catch: this structure is thread-safe β€” except for its destructor method, mongoc_client_pool_destroy(), which is not thread-safe and must only be called from one thread. one. single. thread. don't be brave about it 😭

Example

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:\n"
                        "error message: %s\n",
                        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;
          }

ten threads, one pool, pop and push, pop and push β€” it's giving ✨efficient✨ fr fr


mongoc_client_session_t

use a session for a sequence of operations, optionally with causal consistency. see the MongoDB Manual Entry for Causal Consistency. like a little storyline that ties your operations together 🫢

Synopsis

start a session with mongoc_client_start_session(), use that session for a sequence of operations and multi-document transactions, then free it with mongoc_client_session_destroy().

and here's the cleanup order rule that will bite you if you're not paying attention:

Any mongoc_cursor_t or mongoc_change_stream_t using a session must be destroyed before the session, and a session must be destroyed before the mongoc_client_t it came from. order matters bestie, don't freestyle it πŸ’€

Like, real talk: default sessions are causally consistent. If you're like "no thanks, I'd rather live unbothered," you gotta do it before you start the session β€” create a mongoc_session_opt_t with mongoc_session_opts_new(), then call mongoc_session_opts_set_causal_consistency(), then free the struct with mongoc_session_opts_destroy(). Order matters bestie, don't skip steps πŸ’…

Also: unacknowledged writes are prohibited with sessions. Not "discouraged," not "frowned upon." Prohibited. 🚫

And listen β€” a mongoc_client_session_t must be used by only one thread at a time. Because of session pooling, mongoc_client_start_session() may hand you a session that has been idling for a while and is literally about to get closed once its idle timeout hits. So use your session within one minute of acquiring it β€” that refreshes it and keeps the timeout from snatching it away from you. ⏰

🍴 Fork Safety

A mongoc_client_session_t is only usable in the parent process after a fork. The child process has to call mongoc_client_reset() on the client field. That's the whole vibe check for forking, no cap.

✨ Example ✨

example-session.c β€” presenting, the moment you've all been waiting for πŸ‘‘

/* gcc example-session.c -o example-session \
 *     $(pkg-config --cflags --libs libmongoc-1.0) */

/* ./example-session [CONNECTION_STRING] */

#include <mongoc/mongoc.h>

#include <stdio.h>

int
main(int argc, char *argv[])
{
   int exit_code = EXIT_FAILURE;

   mongoc_client_t *client = NULL;
   const char *uri_string = "mongodb://127.0.0.1/?appname=session-example";
   mongoc_uri_t *uri = NULL;
   mongoc_client_session_t *client_session = NULL;
   mongoc_collection_t *collection = NULL;
   bson_error_t error;
   bson_t *selector = NULL;
   bson_t *update = NULL;
   bson_t *update_opts = NULL;
   bson_t *find_opts = NULL;
   mongoc_read_prefs_t *secondary = NULL;
   mongoc_cursor_t *cursor = NULL;
   const bson_t *doc;
   char *str;
   bool r;

   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:\n"
              "error message: %s\n",
              error.message);
      goto done;
   }

   client = mongoc_client_new_from_uri(uri);
   if (!client) {
      goto done;
   }

   mongoc_client_set_error_api(client, 2);

   /* pass NULL for options - by default the session is causally consistent */
   client_session = mongoc_client_start_session(client, NULL, &error);
   if (!client_session) {
      fprintf(stderr, "Failed to start session: %s\n", error.message);
      goto done;
   }

   collection = mongoc_client_get_collection(client, "test", "collection");
   selector = BCON_NEW("_id", BCON_INT32(1));
   update = BCON_NEW("$inc", "{", "x", BCON_INT32(1), "}");
   update_opts = bson_new();
   if (!mongoc_client_session_append(client_session, update_opts, &error)) {
      fprintf(stderr, "Could not add session to opts: %s\n", error.message);
      goto done;
   }

   r = mongoc_collection_update_one(collection, selector, update, update_opts, NULL /* reply */, &error);

   if (!r) {
      fprintf(stderr, "Update failed: %s\n", error.message);
      goto done;
   }

   bson_destroy(selector);
   selector = BCON_NEW("_id", BCON_INT32(1));
   secondary = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);

   find_opts = BCON_NEW("maxTimeMS", BCON_INT32(2000));
   if (!mongoc_client_session_append(client_session, find_opts, &error)) {
      fprintf(stderr, "Could not add session to opts: %s\n", error.message);
      goto done;
   }

   /* read from secondary. since we're in a causally consistent session, the
    * data is guaranteed to reflect the update we did on the primary. the query
    * blocks waiting for the secondary to catch up, if necessary, or times out
    * and fails after 2000 ms.
    */
   cursor = mongoc_collection_find_with_opts(collection, selector, find_opts, secondary);

   while (mongoc_cursor_next(cursor, &doc)) {
      str = bson_as_relaxed_extended_json(doc, NULL);
      fprintf(stdout, "%s\n", str);
      bson_free(str);
   }

   if (mongoc_cursor_error(cursor, &error)) {
      fprintf(stderr, "Cursor Failure: %s\n", error.message);
      goto done;
   }

   exit_code = EXIT_SUCCESS;

done:
   if (find_opts) {
      bson_destroy(find_opts);
   }
   if (update) {
      bson_destroy(update);
   }
   if (selector) {
      bson_destroy(selector);
   }
   if (update_opts) {
      bson_destroy(update_opts);
   }
   if (secondary) {
      mongoc_read_prefs_destroy(secondary);
   }
   /* destroy cursor, collection, session before the client they came from */
   if (cursor) {
      mongoc_cursor_destroy(cursor);
   }
   if (collection) {
      mongoc_collection_destroy(collection);
   }
   if (client_session) {
      mongoc_client_session_destroy(client_session);
   }
   if (uri) {
      mongoc_uri_destroy(uri);
   }
   if (client) {
      mongoc_client_destroy(client);
   }

   mongoc_cleanup();

   return exit_code;
}

πŸ’« mongoc_client_session_with_transaction_cb_t

Synopsis

typedef bool (*mongoc_client_session_with_transaction_cb_t) (
   mongoc_client_session_t *session,
   void *ctx,
   bson_t **reply,
   bson_error_t *error);

This is the callback you hand over to mongoc_client_session_with_transaction(). It should run a sequence of operations that are meant to live inside a transaction. And here's the thing β€” the callback should not attempt to start or commit transactions. That's not its job, bestie. Stay in your lane πŸ’…

Parameters

  • session: A mongoc_client_session_t.
  • ctx: A void* set to the the user-provided ctx passed to mongoc_client_session_with_transaction(). (Yes, the original says "the the." We're keeping it. Iconic typo energy 🫢)
  • reply: An optional location for a bson_t or NULL. The callback should set this if it runs any operations against the server and receives replies.
  • error: A bson_error_t. The callback should set this if it receives any errors while running operations against the server.

Return

Returns true for success and false on failure. If cb returns false then it should also set error. No silently failing, that's not the move 😭

SEE ALSO: mongoc_client_session_with_transaction()

πŸ–₯️ mongoc_client_t

A single-threaded MongoDB connection. See Connection Pooling. One thread, one client, that's the rule ✨

Synopsis

typedef struct _mongoc_client_t mongoc_client_t;

typedef mongoc_stream_t *(*mongoc_stream_initiator_t) (
   const mongoc_uri_t *uri,
   const mongoc_host_list_t *host,
   void *user_data,
   bson_error_t *error);

mongoc_client_t is an opaque type that gives you access to a MongoDB server, replica set, or sharded cluster. It handles management of the underlying sockets and routes to individual nodes based on mongoc_read_prefs_t or mongoc_write_concern_t. It's giving backstage manager energy honestly 🎬

Streams

The underlying transport for a given client can be customized, wrapped, or straight-up replaced by any implementation that fulfills mongoc_stream_t. You set a custom transport with mongoc_client_set_stream_initiator(). Mix and match, make it yours πŸ¦‹

Thread Safety

mongoc_client_t is NOT thread-safe and should only be used from one thread at a time. Big bold NOT, we're not playing around here ⚠️ When you're in multi-threaded scenarios, the recommendation is that you use the thread-safe mongoc_client_pool_t to retrieve a mongoc_client_t for your thread. That's the whole strategy, iykyk.

Fork Safety

A mongoc_client_t is only usable in the parent process after a fork. The child process must call mongoc_client_reset(). Same fork rules as before, no exceptions 🍴

Example

example-client.c β€” the classic, the blueprint, the main character πŸ‘‘

/* gcc example-client.c -o example-client $(pkg-config --cflags --libs
 * libmongoc-1.0) */

/* ./example-client [CONNECTION_STRING [COLLECTION_NAME]] */

#include <mongoc/mongoc.h>

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   mongoc_cursor_t *cursor;
   bson_error_t error;
   const bson_t *doc;
   const char *collection_name = "test";
   bson_t query;
   char *str;
   const char *uri_string = "mongodb://127.0.0.1/?appname=client-example";
   mongoc_uri_t *uri;

   mongoc_init();
   if (argc > 1) {
      uri_string = argv[1];
   }

   if (argc > 2) {
      collection_name = argv[2];
   }

   uri = mongoc_uri_new_with_error(uri_string, &error);
   if (!uri) {
      fprintf(stderr,
              "failed to parse URI\n"
              "error message: %s\n",
              error.message);
      return EXIT_FAILURE;
   }

   client = mongoc_client_new_from_uri(uri);
   if (!client) {
      return EXIT_FAILURE;
   }

   mongoc_client_set_error_api(client, 2);

   bson_init(&query);
   collection = mongoc_client_get_collection(client, "test", collection_name);
   cursor = mongoc_collection_find_with_opts(collection,
                                             &query,
                                             NULL,  /* additional options */
                                             NULL); /* read prefs, NULL for default */

   while (mongoc_cursor_next(cursor, &doc)) {
      str = bson_as_canonical_extended_json(doc, NULL);
      fprintf(stdout, "%s\n", str);
      bson_free(str);
   }

   if (mongoc_cursor_error(cursor, &error)) {
      fprintf(stderr, "Cursor Failure: %s\n", error.message);
      return EXIT_FAILURE;
   }

   bson_destroy(&query);
   mongoc_cursor_destroy(cursor);
   mongoc_collection_destroy(collection);
   mongoc_uri_destroy(uri);
   mongoc_client_destroy(client);
   mongoc_cleanup();

   return EXIT_SUCCESS;
}

πŸ—‚οΈ mongoc_collection_t

Synopsis

typedef struct _mongoc_collection_t mongoc_collection_t;

mongoc_collection_t gives you access to a MongoDB collection. This handle is useful for actions for most CRUD operations, I.e. insert, update, delete, find, etc. Basically the whole daily routine, she does it all πŸ’–

Read Preferences and Write Concerns

Read preferences and write concerns are inherited from the parent client. And if you want something different, they can be overridden by set_* commands if so desired. Your collection, your choices 🌸


πŸŽ€ mongoc_cursor_t

Client-side cursor abstraction. Very demure, very mindful 🧚

Synopsis

typedef struct _mongoc_cursor_t mongoc_cursor_t;

mongoc_cursor_t provides access to a MongoDB query cursor. It wraps up the wire protocol negotiation required to initiate a query and retrieve an unknown number of documents. Unknown number, like, she doesn't know how many docs are coming and honestly neither do you 😌

Common cursor operations include:

  • Peep which host you actually ended up connected to with mongoc_cursor_get_host() πŸ‘€
  • Keep pulling more records by hitting mongoc_cursor_next() over and over again πŸ”
  • Wanna run that same query again later? Clone it with mongoc_cursor_clone() 🧬
  • Check for problems with mongoc_cursor_error() 🚨

Cursors are lazy β€” and I mean lazy lazy, bestie. Like, no connection gets established and literally zero network traffic happens until your very first call to mongoc_cursor_next(). It's giving "I'll get to it when I get to it" energy and honestly? Respect. ✨


πŸ’… Thread Safety πŸ’…

mongoc_cursor_t is NOT thread safe. Nope. Not even a little. It may only be used from within the thread in which it was created. Periodt. πŸ™…β€β™€οΈ No passing it around to your other threads, that's how you get chaos.

πŸŽ€ Example πŸŽ€

Query MongoDB and iterate results

/* gcc example-client.c -o example-client $(pkg-config --cflags --libs
 * libmongoc-1.0) */

/* ./example-client [CONNECTION_STRING [COLLECTION_NAME]] */

#include <mongoc/mongoc.h>

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   mongoc_cursor_t *cursor;
   bson_error_t error;
   const bson_t *doc;
   const char *collection_name = "test";
   bson_t query;
   char *str;
   const char *uri_string = "mongodb://127.0.0.1/?appname=client-example";
   mongoc_uri_t *uri;

   mongoc_init();
   if (argc > 1) {
      uri_string = argv[1];
   }

   if (argc > 2) {
      collection_name = argv[2];
   }

   uri = mongoc_uri_new_with_error(uri_string, &error);
   if (!uri) {
      fprintf(stderr,
              "failed to parse URI\n"
              "error message: %s\n",
              error.message);
      return EXIT_FAILURE;
   }

   client = mongoc_client_new_from_uri(uri);
   if (!client) {
      return EXIT_FAILURE;
   }

   mongoc_client_set_error_api(client, 2);

   bson_init(&query);
   collection = mongoc_client_get_collection(client, "test", collection_name);
   cursor = mongoc_collection_find_with_opts(collection,
                                             &query,
                                             NULL,  /* additional options */
                                             NULL); /* read prefs, NULL for default */

   while (mongoc_cursor_next(cursor, &doc)) {
      str = bson_as_canonical_extended_json(doc, NULL);
      fprintf(stdout, "%s\n", str);
      bson_free(str);
   }

   if (mongoc_cursor_error(cursor, &error)) {
      fprintf(stderr, "Cursor Failure: %s\n", error.message);
      return EXIT_FAILURE;
   }

   bson_destroy(&query);
   mongoc_cursor_destroy(cursor);
   mongoc_collection_destroy(collection);
   mongoc_uri_destroy(uri);
   mongoc_client_destroy(client);
   mongoc_cleanup();

   return EXIT_SUCCESS;
}

πŸ—„οΈ mongoc_database_t πŸ—„οΈ

MongoDB Database Abstraction

✨ Synopsis ✨

typedef struct _mongoc_database_t mongoc_database_t;

mongoc_database_t gives you access to a MongoDB database. This handle is the vibe for doing stuff with one particular database object β€” but heads up, it is not a container for mongoc_collection_t structures. Don't try to make it hold your collections, that's not its job πŸ™ˆ

Read preferences and write concerns get inherited from the parent client, and you can override them whenever you want with mongoc_database_set_read_prefs() and mongoc_database_set_write_concern(). Customize away πŸ’…

🌸 Examples 🌸

#include <mongoc/mongoc.h>

int
main (int argc, char *argv[])
{
   mongoc_database_t *database;
   mongoc_client_t *client;

   mongoc_init ();

   client = mongoc_client_new ("mongodb://localhost/");
   database = mongoc_client_get_database (client, "test");

   mongoc_database_destroy (database);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return 0;
}

πŸ”§ mongoc_find_and_modify_opts_t πŸ”§

find_and_modify abstraction

✨ Synopsis ✨

mongoc_find_and_modify_opts_t is a builder interface β€” it's how you construct the findAndModify command. Think of it as a little options bag you keep adding to before you send it off πŸŽ€

It exists specifically so new arguments to the findAndModify command could be added without breaking everything. Iconic forward-thinking behaviour, honestly πŸ‘‘

As of MongoDB 3.2, the mongoc_write_concern_t specified on the mongoc_collection_t will be used, if any.

⭐ Example ⭐

flags.c

void
fam_flags(mongoc_collection_t *collection)
{
   mongoc_find_and_modify_opts_t *opts;
   bson_t reply;
   bson_error_t error;
   bson_t query = BSON_INITIALIZER;
   bson_t *update;
   bool success;

   /* Find Zlatan Ibrahimovic, the striker */
   BSON_APPEND_UTF8(&query, "firstname", "Zlatan");
   BSON_APPEND_UTF8(&query, "lastname", "Ibrahimovic");
   BSON_APPEND_UTF8(&query, "profession", "Football player");
   BSON_APPEND_INT32(&query, "age", 34);
   BSON_APPEND_INT32(&query, "goals", (16 + 35 + 23 + 57 + 16 + 14 + 28 + 84) + (1 + 6 + 62));

   /* Add his football position */
   update = BCON_NEW("$set", "{", "position", BCON_UTF8("striker"), "}");

   opts = mongoc_find_and_modify_opts_new();

   mongoc_find_and_modify_opts_set_update(opts, update);

   /* Create the document if it didn't exist, and return the updated document */
   mongoc_find_and_modify_opts_set_flags(opts, MONGOC_FIND_AND_MODIFY_UPSERT | MONGOC_FIND_AND_MODIFY_RETURN_NEW);

   success = mongoc_collection_find_and_modify_with_opts(collection, &query, opts, &reply, &error);

   if (success) {
      char *str;

      str = bson_as_canonical_extended_json(&reply, NULL);
      printf("%s\n", str);
      bson_free(str);
   } else {
      fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, (int)(__LINE__));
   }

   bson_destroy(&reply);
   bson_destroy(update);
   bson_destroy(&query);
   mongoc_find_and_modify_opts_destroy(opts);
}

bypass.c

void
fam_bypass(mongoc_collection_t *collection)
{
   mongoc_find_and_modify_opts_t *opts;
   bson_t reply;
   bson_t *update;
   bson_error_t error;
   bson_t query = BSON_INITIALIZER;
   bool success;

   /* Find Zlatan Ibrahimovic, the striker */
   BSON_APPEND_UTF8(&query, "firstname", "Zlatan");
   BSON_APPEND_UTF8(&query, "lastname", "Ibrahimovic");
   BSON_APPEND_UTF8(&query, "profession", "Football player");

   /* Bump his age */
   update = BCON_NEW("$inc", "{", "age", BCON_INT32(1), "}");

   opts = mongoc_find_and_modify_opts_new();
   mongoc_find_and_modify_opts_set_update(opts, update);
   /* He can still play, even though he is pretty old. */
   mongoc_find_and_modify_opts_set_bypass_document_validation(opts, true);

   success = mongoc_collection_find_and_modify_with_opts(collection, &query, opts, &reply, &error);

   if (success) {
      char *str;

      str = bson_as_canonical_extended_json(&reply, NULL);
      printf("%s\n", str);
      bson_free(str);
   } else {
      fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, (int)(__LINE__));
   }

   bson_destroy(&reply);
   bson_destroy(update);
   bson_destroy(&query);
   mongoc_find_and_modify_opts_destroy(opts);
}

update.c

void
fam_update(mongoc_collection_t *collection)
{
   mongoc_find_and_modify_opts_t *opts;
   bson_t *update;
   bson_t reply;
   bson_error_t error;
   bson_t query = BSON_INITIALIZER;
   bool success;

   /* Find Zlatan Ibrahimovic */
   BSON_APPEND_UTF8(&query, "firstname", "Zlatan");
   BSON_APPEND_UTF8(&query, "lastname", "Ibrahimovic");

   /* Make him a book author */
   update = BCON_NEW("$set", "{", "author", BCON_BOOL(true), "}");

   opts = mongoc_find_and_modify_opts_new();
   /* Note that the document returned is the _previous_ version of the document
    * To fetch the modified new version, use
    * mongoc_find_and_modify_opts_set_flags (opts,
    * MONGOC_FIND_AND_MODIFY_RETURN_NEW);
    */
   mongoc_find_and_modify_opts_set_update(opts, update);

   success = mongoc_collection_find_and_modify_with_opts(collection, &query, opts, &reply, &error);

   if (success) {
      char *str;

      str = bson_as_canonical_extended_json(&reply, NULL);
      printf("%s\n", str);
      bson_free(str);
   } else {
      fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, (int)(__LINE__));
   }

   bson_destroy(&reply);
   bson_destroy(update);
   bson_destroy(&query);
   mongoc_find_and_modify_opts_destroy(opts);
}

fields.c

void
fam_fields(mongoc_collection_t *collection)
{
   mongoc_find_and_modify_opts_t *opts;
   bson_t fields = BSON_INITIALIZER;
   bson_t *update;
   bson_t reply;
   bson_error_t error;
   bson_t query = BSON_INITIALIZER;
   bool success;

   /* Find Zlatan Ibrahimovic */
   BSON_APPEND_UTF8(&query, "lastname", "Ibrahimovic");
   BSON_APPEND_UTF8(&query, "firstname", "Zlatan");

   /* Return his goal tally */
   BSON_APPEND_INT32(&fields, "goals", 1);

   /* Bump his goal tally */
   update = BCON_NEW("$inc", "{", "goals", BCON_INT32(1), "}");

   opts = mongoc_find_and_modify_opts_new();
   mongoc_find_and_modify_opts_set_update(opts, update);
   mongoc_find_and_modify_opts_set_fields(opts, &fields);
   /* Return the new tally */
   mongoc_find_and_modify_opts_set_flags(opts, MONGOC_FIND_AND_MODIFY_RETURN_NEW);

   success = mongoc_collection_find_and_modify_with_opts(collection, &query, opts, &reply, &error);

   if (success) {
      char *str;

      str = bson_as_canonical_extended_json(&reply, NULL);
      printf("%s\n", str);
      bson_free(str);
   } else {
      fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, (int)(__LINE__));
   }

   bson_destroy(&reply);
   bson_destroy(update);
   bson_destroy(&fields);
   bson_destroy(&query);
   mongoc_find_and_modify_opts_destroy(opts);
}

sort.c

void
fam_sort(mongoc_collection_t *collection)
{
   mongoc_find_and_modify_opts_t *opts;
   bson_t *update;
   bson_t sort = BSON_INITIALIZER;
   bson_t reply;
   bson_error_t error;
   bson_t query = BSON_INITIALIZER;
   bool success;

   /* Find all users with the lastname Ibrahimovic */
   BSON_APPEND_UTF8(&query, "lastname", "Ibrahimovic");
             /* Sort by age (descending) */
             BSON_APPEND_INT32(&sort, "age", -1);

             /* Bump his goal tally */
             update = BCON_NEW("$set", "{", "oldest", BCON_BOOL(true), "}");

             opts = mongoc_find_and_modify_opts_new();
             mongoc_find_and_modify_opts_set_update(opts, update);
             mongoc_find_and_modify_opts_set_sort(opts, &sort);

             success = mongoc_collection_find_and_modify_with_opts(collection, &query, opts, &reply, &error);

             if (success) {
                char *str;

                str = bson_as_canonical_extended_json(&reply, NULL);
                printf("%s\n", str);
                bson_free(str);
             } else {
                fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, (int)(__LINE__));
             }

             bson_destroy(&reply);
             bson_destroy(update);
             bson_destroy(&sort);
             bson_destroy(&query);
             mongoc_find_and_modify_opts_destroy(opts);
          }

And bestie, here's the next file in the example set, opts.c β€” this one is literally the options flex πŸ’…:

          void
          fam_opts(mongoc_collection_t *collection)
          {
             mongoc_find_and_modify_opts_t *opts;
             bson_t reply;
             bson_t *update;
             bson_error_t error;
             bson_t query = BSON_INITIALIZER;
             mongoc_write_concern_t *wc;
             bson_t extra = BSON_INITIALIZER;
             bool success;

             /* Find Zlatan Ibrahimovic, the striker */
             BSON_APPEND_UTF8(&query, "firstname", "Zlatan");
             BSON_APPEND_UTF8(&query, "lastname", "Ibrahimovic");
             BSON_APPEND_UTF8(&query, "profession", "Football player");

             /* Bump his age */
             update = BCON_NEW("$inc", "{", "age", BCON_INT32(1), "}");

             opts = mongoc_find_and_modify_opts_new();
             mongoc_find_and_modify_opts_set_update(opts, update);

             /* Abort if the operation takes too long. */
             mongoc_find_and_modify_opts_set_max_time_ms(opts, 100);

             /* Set write concern w: 2 */
             wc = mongoc_write_concern_new();
             mongoc_write_concern_set_w(wc, 2);
             mongoc_write_concern_append(wc, &extra);

             /* Some future findAndModify option the driver doesn't support conveniently
              */
             BSON_APPEND_INT32(&extra, "futureOption", 42);
             mongoc_find_and_modify_opts_append(opts, &extra);

             success = mongoc_collection_find_and_modify_with_opts(collection, &query, opts, &reply, &error);

             if (success) {
                char *str;

                str = bson_as_canonical_extended_json(&reply, NULL);
                printf("%s\n", str);
                bson_free(str);
             } else {
                fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, (int)(__LINE__));
             }

             bson_destroy(&reply);
             bson_destroy(&update);
             bson_destroy(update);
             bson_destroy(&query);
             mongoc_write_concern_destroy(wc);
             mongoc_find_and_modify_opts_destroy(opts);
          }

Oops β€” correction era πŸŽ€: the real file is exactly this, no dupe, take it from the top:

          void
          fam_opts(mongoc_collection_t *collection)
          {
             mongoc_find_and_modify_opts_t *opts;
             bson_t reply;
             bson_t *update;
             bson_error_t error;
             bson_t query = BSON_INITIALIZER;
             mongoc_write_concern_t *wc;
             bson_t extra = BSON_INITIALIZER;
             bool success;

             /* Find Zlatan Ibrahimovic, the striker */
             BSON_APPEND_UTF8(&query, "firstname", "Zlatan");
             BSON_APPEND_UTF8(&query, "lastname", "Ibrahimovic");
             BSON_APPEND_UTF8(&query, "profession", "Football player");

             /* Bump his age */
             update = BCON_NEW("$inc", "{", "age", BCON_INT32(1), "}");

             opts = mongoc_find_and_modify_opts_new();
             mongoc_find_and_modify_opts_set_update(opts, update);

             /* Abort if the operation takes too long. */
             mongoc_find_and_modify_opts_set_max_time_ms(opts, 100);

             /* Set write concern w: 2 */
             wc = mongoc_write_concern_new();
             mongoc_write_concern_set_w(wc, 2);
             mongoc_write_concern_append(wc, &extra);

             /* Some future findAndModify option the driver doesn't support conveniently
              */
             BSON_APPEND_INT32(&extra, "futureOption", 42);
             mongoc_find_and_modify_opts_append(opts, &extra);

             success = mongoc_collection_find_and_modify_with_opts(collection, &query, opts, &reply, &error);

             if (success) {
                char *str;

                str = bson_as_canonical_extended_json(&reply, NULL);
                printf("%s\n", str);
                bson_free(str);
             } else {
                fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, (int)(__LINE__));
             }

             bson_destroy(&reply);
             bson_destroy(&extra);
             bson_destroy(update);
             bson_destroy(&query);
             mongoc_write_concern_destroy(wc);
             mongoc_find_and_modify_opts_destroy(opts);
          }

(ngl, peek at the top: update is a bson_t * from BCON_NEW, and the cleanup below it is bson_destroy(update); β€” the & only shows up on the stack-allocated query and extra. Also the &update in the destroy call is the only line that differs between the two passes, so always copy the last one, bestie πŸ’€)


Okay and now the main character herself: fam.c 🫢

          int
          main(void)
          {
             mongoc_collection_t *collection;
             mongoc_database_t *database;
             mongoc_client_t *client;
             const char *uri_string = "mongodb://localhost:27017/admin?appname=find-and-modify-opts-example";
             mongoc_uri_t *uri;
             bson_error_t error;
             bson_t *options;

             mongoc_init();

             uri = mongoc_uri_new_with_error(uri_string, &error);
             if (!uri) {
                fprintf(stderr,
                        "failed to parse URI:\n"
                        "error message: %s\n",
                        error.message);
                return EXIT_FAILURE;
             }

             client = mongoc_client_new_from_uri(uri);
             if (!client) {
                return EXIT_FAILURE;
             }

             mongoc_client_set_error_api(client, 2);
             database = mongoc_client_get_database(client, "databaseName");

             options = BCON_NEW("validator",
                                "{",
                                "age",
                                "{",
                                "$lte",
                                BCON_INT32(34),
                                "}",
                                "}",
                                "validationAction",
                                BCON_UTF8("error"),
                                "validationLevel",
                                BCON_UTF8("moderate"));

             collection = mongoc_database_create_collection(database, "collectionName", options, &error);
             if (!collection) {
                fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, (int)(__LINE__));
                return EXIT_FAILURE;
             }

             fam_flags(collection);
             fam_bypass(collection);
             fam_update(collection);
             fam_fields(collection);
             fam_opts(collection);
             fam_sort(collection);

             mongoc_collection_drop(collection, NULL);
             bson_destroy(options);
             mongoc_uri_destroy(uri);
             mongoc_database_destroy(database);
             mongoc_collection_destroy(collection);
             mongoc_client_destroy(client);

             mongoc_cleanup();
             return EXIT_SUCCESS;
          }

<h4>✨ Outputs:</h4>

          {
              "lastErrorObject": {
                  "updatedExisting": false,
                  "n": 1,
                  "upserted": {
                      "$oid": "56562a99d13e6d86239c7b00"
                  }
              },
              "value": {
                  "_id": {
                      "$oid": "56562a99d13e6d86239c7b00"
                  },
                  "age": 34,
                  "firstname": "Zlatan",
                  "goals": 342,
                  "lastname": "Ibrahimovic",
                  "profession": "Football player",
                  "position": "striker"
              },
              "ok": 1
          }
          {
              "lastErrorObject": {
                  "updatedExisting": true,
                  "n": 1
              },
              "value": {
                  "_id": {
                      "$oid": "56562a99d13e6d86239c7b00"
                  },
                  "age": 34,
                  "firstname": "Zlatan",
                  "goals": 342,
                  "lastname": "Ibrahimovic",
                  "profession": "Football player",
                  "position": "striker"
              },
              "ok": 1
          }
          {
              "lastErrorObject": {
                  "updatedExisting": true,
                  "n": 1
              },
              "value": {
                  "_id": {
                      "$oid": "56562a99d13e6d86239c7b00"
                  },
                  "age": 35,
                  "firstname": "Zlatan",
                  "goals": 342,
                  "lastname": "Ibrahimovic",
                  "profession": "Football player",
                  "position": "striker"
              },
              "ok": 1
          }
          {
              "lastErrorObject": {
                  "updatedExisting": true,
                  "n": 1
              },
              "value": {
                  "_id": {
                      "$oid": "56562a99d13e6d86239c7b00"
                  },
                  "goals": 343
              },
              "ok": 1
          }
          {
              "lastErrorObject": {
                  "updatedExisting": true,
                  "n": 1
              },
              "value": {
                  "_id": {
                      "$oid": "56562a99d13e6d86239c7b00"
                  },
                  "age": 35,
                  "firstname": "Zlatan",
                  "goals": 343,
                  "lastname": "Ibrahimovic",
                  "profession": "Football player",
                  "position": "striker",
                  "author": true
              },
              "ok": 1
          }

πŸŽ€ mongoc_gridfs_file_list_t πŸŽ€

Synopsis

          #include <mongoc/mongoc.h>

          typedef struct _mongoc_gridfs_file_list_t mongoc_gridfs_file_list_t;

Description

So mongoc_gridfs_file_list_t is your <b>gridfs file list abstraction</b>, bestie. It hands you iteration plus basic marshalling sitting right on top of a regular mongoc_collection_find_with_opts()-style query. And the interface? Lowkey styled after mongoc_cursor_t β€” so if you already know the cursor, you're literally at home already 🏠✨

Example

          mongoc_gridfs_file_list_t *list;
          mongoc_gridfs_file_t *file;

          list = mongoc_gridfs_find_with_opts (gridfs, query, NULL);

          while ((file = mongoc_gridfs_file_list_next (list))) {
             do_something (file);

             mongoc_gridfs_file_destroy (file);
          }

          mongoc_gridfs_file_list_destroy (list);

🌸 mongoc_gridfs_file_opt_t 🌸

Synopsis

          typedef struct {
             const char *md5;
             const char *filename;
             const char *content_type;
             const bson_t *aliases;
             const bson_t *metadata;
             uint32_t chunk_size;
          } mongoc_gridfs_file_opt_t;

Description

This lil struct is a bag of options you can set on a mongoc_gridfs_file_t. Various functions reach for it when they're creating a new gridfs file β€” so it's the "here's how I want my file born" form, no cap πŸ’…


πŸ¦‹ mongoc_gridfs_file_t πŸ¦‹

Synopsis

          typedef struct _mongoc_gridfs_file_t mongoc_gridfs_file_t;

Description

Okay so this is the MongoDB GridFS file abstraction β€” the actual file object, and she provides several APIs:

  • readv, writev, seek, and tell.
  • General file metadata such as filename and length.
  • GridFS metadata such as md5, filename, content_type, aliases, metadata, chunk_size, and upload_date.

Thread Safety

⚠️ This structure is <b>NOT</b> thread-safe, bestie 😭 Only use it from <b>one thread at a time</b>, periodt. Don't be out here sharing her with your whole friend group.
  • mongoc_client_t
  • mongoc_gridfs_t
  • mongoc_gridfs_file_list_t
  • mongoc_gridfs_file_opt_t

πŸ‘‘ mongoc_gridfs_bucket_t πŸ‘‘

Synopsis

          #include <mongoc/mongoc.h>

          typedef struct _mongoc_gridfs_bucket_t mongoc_gridfs_bucket_t;

Description

mongoc_gridfs_bucket_t gives you a <b>spec-compliant MongoDB GridFS implementation</b>, and she's superseding mongoc_gridfs_t β€” like, the older one is cute but this is the upgrade ✨ Peep the GridFS MongoDB documentation for the full tea.

Thread Safety

⚠️ mongoc_gridfs_bucket_t is <b>NOT</b> thread-safe, and she should only ever be used in the <b>same thread as the owning mongoc_client_t</b>. Same-thread only, iykyk πŸ’€

Lifecycle

It is an <b>error</b> to free a mongoc_gridfs_bucket_t <b>before freeing all derived instances of mongoc_stream_t</b> 🚨 And the owning mongoc_client_t <b>must outlive</b> the mongoc_gridfs_bucket_t. Cleanup order is real, don't skip it πŸ™ˆ

Example

Behold: example-gridfs-bucket.c πŸŽ€

          #include <mongoc/mongoc.h>

          #include <stdio.h>
          #include <stdlib.h>

          int
          main(int argc, char *argv[])
          {
             const char *uri_string = "mongodb://localhost:27017/?appname=new-gridfs-example";
             mongoc_client_t *client;
             mongoc_database_t *db;
             mongoc_stream_t *file_stream;
             mongoc_gridfs_bucket_t *bucket;
             mongoc_cursor_t *cursor;
             bson_t filter;
             bool res;
             bson_value_t file_id;
             bson_error_t error;
             const bson_t *doc;
             char *str;
             mongoc_init();

             if (argc != 3) {
                fprintf(stderr, "usage: %s SOURCE_FILE_PATH FILE_COPY_PATH\n", argv[0]);
                return EXIT_FAILURE;
             }

…and that's where this chunk runs out, bestie β€” the code keeps going in the next part 🫢✨

/* 1. Make a bucket. */
client = mongoc_client_new(uri_string);
db = mongoc_client_get_database(client, "test");
bucket = mongoc_gridfs_bucket_new(db, NULL, NULL, &error);
if (!bucket) {
   printf("Error creating gridfs bucket: %s\n", error.message);
   return EXIT_FAILURE;
}

/* 2. Insert a file.  */
file_stream = mongoc_stream_file_new_for_path(argv[1], O_RDONLY, 0);
res = mongoc_gridfs_bucket_upload_from_stream(bucket, "my-file", file_stream, NULL, &file_id, &error);
if (!res) {
   printf("Error uploading file: %s\n", error.message);
   return EXIT_FAILURE;
}

mongoc_stream_close(file_stream);
mongoc_stream_destroy(file_stream);

/* 3. Download the file in GridFS to a local file. */
file_stream = mongoc_stream_file_new_for_path(argv[2], O_CREAT | O_RDWR, 0);
if (!file_stream) {
   perror("Error opening file stream");
   return EXIT_FAILURE;
}

res = mongoc_gridfs_bucket_download_to_stream(bucket, &file_id, file_stream, &error);
if (!res) {
   printf("Error downloading file to stream: %s\n", error.message);
   return EXIT_FAILURE;
}
mongoc_stream_close(file_stream);
mongoc_stream_destroy(file_stream);

/* 4. List what files are available in GridFS. */
bson_init(&filter);
cursor = mongoc_gridfs_bucket_find(bucket, &filter, NULL);

while (mongoc_cursor_next(cursor, &doc)) {
   str = bson_as_canonical_extended_json(doc, NULL);
   printf("%s\n", str);
   bson_free(str);
}

/* 5. Delete the file that we added. */
res = mongoc_gridfs_bucket_delete_by_id(bucket, &file_id, &error);
if (!res) {
   printf("Error deleting the file: %s\n", error.message);
   return EXIT_FAILURE;
}

/* 6. Cleanup. */
mongoc_stream_close(file_stream);
mongoc_stream_destroy(file_stream);
mongoc_cursor_destroy(cursor);
bson_destroy(&filter);
mongoc_gridfs_bucket_destroy(bucket);
mongoc_database_destroy(db);
mongoc_client_destroy(client);
mongoc_cleanup();

return EXIT_SUCCESS;
}

Yup, that's the whole lil' six-step era β€” make a bucket, shove a file in, pull it back out, list the vibes, yeet the file, clean up your mess like a responsible icon πŸ’…βœ¨

SEE ALSO πŸ”

  • The MongoDB GridFS specification.
  • The non spec-compliant mongoc_gridfs_t.

πŸ¦‹ mongoc_gridfs_t πŸ¦‹

WARNING: This GridFS implementation does not conform to the MongoDB GridFS specification. For a spec compliant implementation, use mongoc_gridfs_bucket_t. Like, genuinely, bestie β€” read this warning twice. βœ‹

Synopsis ✨

#include <mongoc/mongoc.h>

typedef struct _mongoc_gridfs_t mongoc_gridfs_t;

Description πŸ’–

mongoc_gridfs_t gives you a MongoDB gridfs implementation. The whole system is made up of gridfs objects, which contain gridfs_files and gridfs_file_lists β€” so basically it's a whole little file system API, cute right? πŸŽ€

There are, and I cannot stress this enough, extensive caveats about what kind of use cases gridfs is actually practical for. Especially: any writing after the initial file creation is likely to both break any concurrent readers and be like, super expensive. That said, this implementation does let you do arbitrary writes to an existing gridfs object β€” just use them with caution, okay? πŸ™ˆ

mongoc_gridfs also integrates super tightly with the mongoc_stream_t abstraction, which gives you some convenient wrapping for file creation and reading/writing. You can totally use it without that, but ngl it's worth peeking at to see if your problem can fit that model. πŸ‘€

WARNING: mongoc_gridfs_t does not support read preferences. In a replica set, GridFS queries are always routed to the primary. No choosing, no vibes check, just primary. periodt.

Thread Safety 🧡

mongoc_gridfs_t is NOT thread-safe and should only ever be used in the same thread as the owning mongoc_client_t. Like, same thread, same energy, no splitting up the squad. πŸ’€

Lifecycle 🌱

It is an error to free a mongoc_gridfs_t before freeing all related instances of mongoc_gridfs_file_t and mongoc_gridfs_file_list_t. Clean up your children first, bestie, that's just manners. 🫢

Example 🌸

example-gridfs.c

#include <mongoc/mongoc.h>

#include <fcntl.h>

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
   mongoc_gridfs_t *gridfs;
   mongoc_gridfs_file_t *file;
   mongoc_gridfs_file_list_t *list;
   mongoc_gridfs_file_opt_t opt = {0};
   mongoc_client_t *client;
   const char *uri_string = "mongodb://127.0.0.1:27017/?appname=gridfs-example";
   mongoc_uri_t *uri;
   mongoc_stream_t *stream;
   bson_t filter;
   bson_t opts;
   bson_t child;
   bson_error_t error;
   ssize_t r;
   char buf[4096];
   mongoc_iovec_t iov;
   const char *filename;
   const char *command;
   bson_value_t id;

   if (argc < 2) {
      fprintf(stderr, "usage - %s command ...\n", argv[0]);
      return EXIT_FAILURE;
   }

   mongoc_init();

   iov.iov_base = (void *)buf;
   iov.iov_len = sizeof buf;

   /* connect to localhost client */
   uri = mongoc_uri_new_with_error(uri_string, &error);
   if (!uri) {
      fprintf(stderr,
              "failed to parse URI:\n"
              "error message: %s\n",
              error.message);
      return EXIT_FAILURE;
   }

   client = mongoc_client_new_from_uri(uri);
   assert(client);
   mongoc_client_set_error_api(client, 2);

   /* grab a gridfs handle in test prefixed by fs */
   gridfs = mongoc_client_get_gridfs(client, "test", "fs", &error);
   assert(gridfs);

   command = argv[1];
   filename = argv[2];

   if (strcmp(command, "read") == 0) {
      if (argc != 3) {
         fprintf(stderr, "usage - %s read filename\n", argv[0]);
         return EXIT_FAILURE;
      }
      file = mongoc_gridfs_find_one_by_filename(gridfs, filename, &error);
      assert(file);

      stream = mongoc_stream_gridfs_new(file);
      assert(stream);

      for (;;) {
         r = mongoc_stream_readv(stream, &iov, 1, -1, 0);

         assert(r >= 0);

         if (r == 0) {
            break;
         }

         if (fwrite(iov.iov_base, 1, r, stdout) != (size_t)r) {
            fprintf(stderr, "Failed to write to stdout. Exiting.\n");
            exit(1);
         }
      }

      mongoc_stream_destroy(stream);
      mongoc_gridfs_file_destroy(file);
   } else if (strcmp(command, "list") == 0) {
      bson_init(&filter);

      bson_init(&opts);
      bson_append_document_begin(&opts, "sort", -1, &child);
      BSON_APPEND_INT32(&child, "filename", 1);
      bson_append_document_end(&opts, &child);

      list = mongoc_gridfs_find_with_opts(gridfs, &filter, &opts);

      bson_destroy(&filter);
      bson_destroy(&opts);

      while ((file = mongoc_gridfs_file_list_next(list))) {
         const char *name = mongoc_gridfs_file_get_filename(file);
         printf("%s\n", name ? name : "?");

         mongoc_gridfs_file_destroy(file);
      }

      mongoc_gridfs_file_list_destroy(list);
   } else if (strcmp(command, "write") == 0) {
      if (argc != 4) {
         fprintf(stderr, "usage - %s write filename input_file\n", argv[0]);
         return EXIT_FAILURE;
      }

      stream = mongoc_stream_file_new_for_path(argv[3], O_RDONLY, 0);
      assert(stream);

      opt.filename = filename;

      /* the driver generates a file_id for you */
      file = mongoc_gridfs_create_file_from_stream(gridfs, stream, &opt);
      assert(file);

      id.value_type = BSON_TYPE_INT32;
      id.value.v_int32 = 1;

      /* optional: the following method specifies a file_id of any
         BSON type */
      if (!mongoc_gridfs_file_set_id(file, &id, &error)) {
         fprintf(stderr, "%s\n", error.message);
         return EXIT_FAILURE;
      }

      if (!mongoc_gridfs_file_save(file)) {
         mongoc_gridfs_file_error(file, &error);
         fprintf(stderr, "Could not save: %s\n", error.message);
         return EXIT_FAILURE;
      }

      mongoc_gridfs_file_destroy(file);
   } else {
      fprintf(stderr, "Unknown command");
      return EXIT_FAILURE;
   }

   mongoc_gridfs_destroy(gridfs);
   mongoc_uri_destroy(uri);
   mongoc_client_destroy(client);

   mongoc_cleanup();

   return EXIT_SUCCESS;
}

SEE ALSO πŸ”

  • The MongoDB GridFS specification.
  • The spec-compliant mongoc_gridfs_bucket_t. (yes, the good one πŸ’–)

🌈 mongoc_host_list_t 🌈

Synopsis ✨

typedef struct {
   mongoc_host_list_t *next;
   char host[BSON_HOST_NAME_MAX + 1];
   char host_and_port[BSON_HOST_NAME_MAX + 7];
   uint16_t port;
   int family;
   void *padding[4];
} mongoc_host_list_t;

Description πŸ’–

It's the host and port of a MongoDB server, bestie. And it can be part of a linked list β€” like, for example the return value of mongoc_uri_get_hosts() when multiple hosts are provided in the MongoDB URI. Look at it, being all social. πŸ”—

SEE ALSO πŸ”

  • mongoc_uri_get_hosts()
  • mongoc_cursor_get_host()

πŸ”₯ mongoc_insert_flags_t πŸ”₯

Flags for insert operations πŸ’«

Synopsis ✨

typedef enum {
   MONGOC_INSERT_NONE = 0,
   MONGOC_INSERT_CONTINUE_ON_ERROR = 1 << 0,
} mongoc_insert_flags_t;

#define MONGOC_INSERT_NO_VALIDATE (1U << 31)

Description πŸ’–

These flags correspond to the MongoDB wire protocol. They may be bitwise or'd together β€” go ahead, mix 'em, that's literally the whole point. They may modify how an insert happens on the MongoDB server. ✨

🚩 Flag Values

  • MONGOC_INSERT_NONE β€” literally just "no insert flags, thanks." The beige flag of insertion options πŸŽ€
  • MONGOC_INSERT_CONTINUE_ON_ERROR β€” keeps inserting the rest of the documents in your insertion set even if one of them flops. One bad doc doesn't take down the whole squad πŸ’…
  • MONGOC_INSERT_NO_VALIDATE β€” skips validating your documents before doing the insert. Validation can be expensive, so this saves you some time if you already know your documents are valid. iykyk β€” don't come crying if they weren't 😭

🧡 mongoc_iovec_t

Synopsis

Synopsis

bestie it genuinely says Synopsis twice in a row, I'm not making this up πŸ’€ anyway β€”
#include <mongoc/mongoc.h>

#ifdef _WIN32
typedef struct {
   u_long iov_len;
   char *iov_base;
} mongoc_iovec_t;
#else
typedef struct iovec mongoc_iovec_t;
#endif

The mongoc_iovec_t structure is a portability abstraction for consumers of the mongoc_stream_t interfaces. It's what lets you do scatter/gather I/O through the socket subsystem β€” iconic behavior, honestly ✨

WARNING: ⚠️ if you're writing portable code, beware of the ordering of iov_len and iov_base, because those two get flipped around on different platforms. Which means: do not use C initializers to initialize this. Seriously. Don't. πŸ™ˆ

πŸͺͺ mongoc_oidc_callback_fn_t

Synopsis

typedef mongoc_oidc_credential_t *(*mongoc_oidc_callback_fn_t) (mongoc_oidc_callback_params_t *params);

This is the function pointer type stored by mongoc_oidc_callback_t. Yeah. That's the whole vibe.

Parameters

  • params: a mongoc_oidc_callback_params_t object representing the in/out parameters of a mongoc_oidc_callback_t.

Returns

A mongoc_oidc_credential_t object created with mongoc_oidc_credential_new(), or NULL to indicate an error or timeout. Here's the rules, no cap:

  • The function MUST return a mongoc_oidc_credential_t object to indicate success. πŸŽ‰
  • The function MUST return NULL to indicate an error. πŸ’€
  • The function MUST call mongoc_oidc_callback_params_cancel_with_timeout() before returning NULL to indicate a timeout instead of an error.

The cancel_with_timeout out parameter gets ignored if the return value is not NULL. Periodt.

SEE ALSO:

  • mongoc_oidc_callback_t
  • mongoc_oidc_callback_params_t
  • mongoc_oidc_credential_t

πŸ“¦ mongoc_oidc_callback_params_t

Synopsis

typedef struct _mongoc_oidc_callback_params_t mongoc_oidc_callback_params_t;

This bad boy represents the in/out parameters of a mongoc_oidc_callback_t 🫢

The parameters get passed to the mongoc_oidc_callback_fn_t stored inside an mongoc_oidc_callback_t object when it's invoked by a mongoc_client_t or mongoc_client_pool_t object.

Parameters

Here's the current roster of supported parameters:

  • version β€” Versions: 1 β€” the current OIDC callback API version number.
  • user_data β€” Versions: 1 β€” a pointer to data you, the user, provided.
  • timeout β€” Versions: 1 β€” the timestamp after which the callback function must report a timeout.
  • username β€” Versions: 1 β€” the username specified by the URI of the associated client object.
  • cancel_with_timeout β€” Versions: 1 β€” an out parameter indicating cancellation of the callback function due to a timeout instead of an error.

The "Version" column indicates the OIDC callback API versions for which the parameter is applicable. (Yes, the column header says "Versions" and the sentence says "Version" β€” that's the manpage's business, not mine 🌸)

Version

The version parameter is how the OIDC callback API communicates backward compatible changes β€” like when a new parameter gets added. It's the API's little "hey, heads up" text. πŸ“±

You can use this parameter to detect when existing usage of mongoc_oidc_callback_t or a relevant callback function might need to be reviewed.

Fr fr, users can drop a check like this into their callback function:

mongoc_oidc_credential_t *
example_callback_fn (mongoc_oidc_callback_params_t *params)
{
   // A runtime message that new features are available in the OIDC Callback API.
   if (mongoc_oidc_callback_params_get_version (params) > 1) {
      printf ("OIDC Callback API has been updated to a new version!");
   }

   // ...
}

User Data

The user_data parameter is your little side-channel: pass extra arguments into the callback function, or return extra values out of it. Very main character of it πŸ’…

You must set this parameter in advance via mongoc_oidc_callback_set_user_data() before the mongoc_oidc_callback_t object gets associated with a mongoc_client_t or mongoc_client_pool_t object.

WARNING: ⚠️ the lifetime of the object pointed to by user_data is managed the user, not by mongoc_oidc_callback_t! So you own that memory, bestie. You. 🫡
typedef struct {
   int counter;
   const char *error_message;
} user_data_t;

mongoc_oidc_credential_t *
example_callback_fn (mongoc_oidc_callback_params_t *params)
{
   user_data_t *user_data = (user_data_t *) mongoc_oidc_callback_params_get_user_data (params);

   user_data->counter += 1;

   // ...

   if (/* ... */) {
      user_data->error_message = "OIDC callback failed due to ...";
      return NULL;
   }

   // ...
}

void
example (void)
{
   mongoc_client_t *client = /* ... */;
   bson_error_t error;

   {
      user_data_t *user_data = malloc (sizeof (*user_data));
      *user_data = (user_data_t){.counter = 0, .error_message = NULL};
      mongoc_oidc_callback_t *callback = mongoc_oidc_callback_new_with_user_data (&example_callback_fn, (void *) user_data);
      BSON_ASSERT (mongoc_client_set_oidc_callback (client, callback));
      mongoc_oidc_callback_destroy (callback);
   }

   // ... client operations ...

   {
      const mongoc_oidc_callback_t *callback = mongoc_client_get_oidc_callback (client);
      user_data_t *user_data = (user_data_t *) mongoc_oidc_callback_get_user_data (callback);

      if (error.code != 0) {
         printf ("client error message: %s\n", error.message);
      }

      if (user_data->error_message) {
         printf ("custom error message: %s\n", user_data->error_message);
      }

      printf ("The callback function was invoked %d times!", user_data->counter);

      free (user_data);
   }

   mongoc_client_destroy (client);
}

Timeout

The timeout parameter is how the callback function knows when it should report cancellation due to a timeout ⏰

When System Clock is greater than timeout, the callback function must invoke mongoc_oidc_callback_params_cancel_with_timeout() and return NULL.

Username

The username parameter is the value of the username component of the URI of the associated mongoc_client_t or mongoc_client_pool_t object β€” the one the callback function gets invoked from. So it's like, whose URI is this anyway πŸ”

Cancel With Timeout

The cancel_with_timeout out parameter indicates cancellation of the callback function due to a timeout instead of an error. Big difference, don't mix 'em up πŸ’€

IMPORTANT: 🚨 the callback function MUST return NULL, otherwise the invocation gets interpreted as a success even when cancel_with_timeout is set. That's the trap. Do not fall in it.
mongoc_oidc_credential_t *
example_callback_fn (mongoc_oidc_callback_params_t *params) {
   const int64_t *timeout = mongoc_oidc_callback_params_get_timeout (params);

   // NULL means "infinite" timeout.
   if (timeout && bson_get_monotonic_time () > *timeout) {
      return mongoc_oidc_callback_params_cancel_with_timeout (params);
   }

   // ...
}

🚨 Error Handling 🚨

ok so listen β€” a NULL return value (and without setting cancel_with_timeout, bestie, that detail matters) means "we couldn't get you an access token, there was an error." that's the signal. 😭

IMPORTANT: the callback function MUST return NULL, ok?? otherwise the invocation gets interpreted as a success and everything goes sideways. like, no cap, this is the whole vibe check right here. πŸ’€
mongoc_oidc_credential_t *
example_callback_fn (mongoc_oidc_callback_params_t *params) {
   // ...

   if (/* ... */) {
      // The OIDC callback function could not provide an access token due to an error.
      return NULL;
   }

   // ...
}

SEE ALSO:

  • mongoc_oidc_callback_t
  • mongoc_oidc_callback_fn_t

✨ mongoc_oidc_callback_t ✨

Synopsis

typedef struct _mongoc_oidc_callback_t mongoc_oidc_callback_t;

mongoc_oidc_callback_t is literally just a wrapper for your own user-defined callback function, mongoc_oidc_callback_fn_t, that hands back an OIDC access token. iconic behavior honestly. πŸŽ€

the whole point? it lets you plug into OIDC providers that the built-in provider integrations don't support (peep Authentication Mechanism Properties for those, iykyk). πŸ¦‹

Lifecycle 🌱

the function β€” plus any optional user data β€” that's stored by a mongoc_oidc_callback_t must outlive any associated client or client pool object that might invoke the stored callback function. like, don't let it die first, bestie, that's a whole mess. πŸ’…

Thread Safety πŸ”’

the callback function sitting inside a mongoc_oidc_callback_t object gets invoked by at most one thread at a time for an associated mongoc_client_t or mongoc_client_pool_t object. slay, no locking drama:

static mongoc_oidc_credential_t *
single_thread_only (mongoc_oidc_callback_params_t *params)
{
   // This function does not need to support invocation by more than thread at a time.

   // ...
}

void
with_single_client (void)
{
   mongoc_client_t *client = /* ... */;

   {
      mongoc_oidc_callback_t *callback = mongoc_oidc_callback_new (&single_thread_only);
      BSON_ASSERT (mongoc_client_set_oidc_callback (client, callback));
      mongoc_oidc_callback_destroy (callback);
   }

   // ... client operations ...

   mongoc_client_destroy (client);
}

void
with_single_pool (void)
{
   mongoc_client_pool_t *pool = /* ... */;

   {
      mongoc_oidc_callback_t *callback = mongoc_oidc_callback_new (&single_thread_only);
      BSON_ASSERT (mongoc_client_pool_set_oidc_callback (pool, callback));
      mongoc_oidc_callback_destroy (callback);
   }

   // ... client pool operations ...

   mongoc_client_pool_destroy (pool);
}

BUT. 🫢 if your callback is associated with more than one mongoc_client_t object (in multiple threads), or with more than one mongoc_client_pool_t object (even in a single thread), then the callback function MUST support invocation by more than one thread at a time. no exceptions, fr fr:

static mongoc_oidc_credential_t *
many_threads_possible (mongoc_oidc_callback_params_t *params)
{
   // This function MUST support invocation by more than one thread at a time.

   // ...
}

void
with_many_clients (void)
{
   mongoc_client_t *client_a = /* ... */;
   mongoc_client_t *client_b = /* ... */;

   {
      mongoc_oidc_callback_t *callback = mongoc_oidc_callback_new (&many_threads_possible);
      BSON_ASSERT (mongoc_client_set_oidc_callback (client_a, callback));
      BSON_ASSERT (mongoc_client_set_oidc_callback (client_b, callback));
      mongoc_oidc_callback_destroy (callback);
   }

   pthread_t thread_a;
   pthread_t thread_b;

   if (pthread_create (&thread_a, NULL, /* thread_a_fn */, client_a) != 0) { /* ... */ }
   if (pthread_create (&thread_b, NULL, /* thread_b_fn */, client_b) != 0) { /* ... */ }

   // ... client operations using multiple threads ...

   if (pthread_join (&thread_a, NULL) != 0) { /* ... */ }
   if (pthread_join (&thread_b, NULL) != 0) { /* ... */ }

   mongoc_client_destroy (client_a);
   mongoc_client_destroy (client_b);
}

void
with_many_pools (void)
{
   mongoc_client_pool_t *pool_a = /* ... */;
   mongoc_client_pool_t *pool_b = /* ... */;

   {
      mongoc_oidc_callback_t *callback = mongoc_oidc_callback_new (&many_threads_possible);
      BSON_ASSERT (mongoc_client_pool_set_oidc_callback (pool_a, callback));
      BSON_ASSERT (mongoc_client_pool_set_oidc_callback (pool_b, callback));
      mongoc_oidc_callback_destroy (callback);
   }

   // ... client operations using multiple client pools ...

   mongoc_client_pool_destroy (pool_a);
   mongoc_client_pool_destroy (pool_b);
}

SEE ALSO:

  • mongoc_client_t
  • mongoc_client_pool_t
  • mongoc_oidc_callback_fn_t
  • mongoc_oidc_callback_params_t
  • mongoc_oidc_credential_t

🌸 mongoc_oidc_credential_t 🌸

Synopsis

typedef struct _mongoc_oidc_credential_t mongoc_oidc_credential_t;

this bad boy represents the return value of a mongoc_oidc_callback_fn_t. πŸ’–

so here's the tea: the value gets returned by the mongoc_oidc_callback_fn_t that's stored in an mongoc_oidc_callback_t object, whenever an associated mongoc_client_t or mongoc_client_pool_t object invokes it. that's the whole flow ✨

Return Values 🎁

the list of currently supported return values, bestie β€” drink it in:

  • access_token β€” Versions: 1 β€” The OIDC access token.
  • expires_in β€” Versions: 1 β€” An optional expiration duration (in milliseconds).

the "Version" column indicates the OIDC callback API versions for which the parameter is applicable. πŸ“‹

Access Token πŸ”‘

an OIDC access token (a signed JWT token).

WARNING: access_token is NOT directly validated by the driver. πŸ‘€ like, the driver is trusting you here. that's it. that's the warning.

Expiry Duration ⏳

an optional expiry duration (in milliseconds) for the access token.

IMPORTANT: an unset value is interpreted as an infinite expiry duration. forever token, basically. 🫢

SEE ALSO:

  • mongoc_oidc_callback_t
  • mongoc_oidc_callback_fn_t

πŸŽ€ mongoc_optional_t πŸŽ€

a struct to store optional boolean values. yes, optional booleans. we love a tri-state moment.

Synopsis

used to specify optional boolean flags, which may remain unset. πŸ‘»

this is used within mongoc_server_api_t to track whether a flag was explicitly set. like, "did you actually say false or did you just not say anything?" iconic distinction, tbh. πŸ’…


πŸ”₯ mongoc_query_flags_t πŸ”₯

flags for query operations. let's GO.

Synopsis

typedef enum {
   MONGOC_QUERY_NONE = 0,
   MONGOC_QUERY_TAILABLE_CURSOR = 1 << 1,
   MONGOC_QUERY_SECONDARY_OK = 1 << 2,
   MONGOC_QUERY_OPLOG_REPLAY = 1 << 3,
   MONGOC_QUERY_NO_CURSOR_TIMEOUT = 1 << 4,
   MONGOC_QUERY_AWAIT_DATA = 1 << 5,
   MONGOC_QUERY_EXHAUST = 1 << 6,
   MONGOC_QUERY_PARTIAL = 1 << 7,
} mongoc_query_flags_t;

Description 🌈

these flags correspond to the MongoDB wire protocol, periodt. you can bitwise-or them together (go off, bitwise operators πŸ’…) and they may modify how a query is performed in the MongoDB server. cute, powerful, exactly what you'd expect. ⭐

Flag Values

Okay so these are the query flag values, one per bullet, no skipping 😀

  • MONGOC_QUERY_NONE β€” literally just "specify no query flags." that's it, that's the whole vibe.
  • MONGOC_QUERY_TAILABLE_CURSOR β€” the cursor will not be closed when the last data is retrieved, so you can resume it later. it's giving "to be continued…" energy.
  • MONGOC_QUERY_SECONDARY_OK β€” lets you query replica set secondaries. yes queen, spread the reads around.
  • MONGOC_QUERY_OPLOG_REPLAY β€” used internally by MongoDB. not your business, bestie πŸ™ˆ
  • MONGOC_QUERY_NO_CURSOR_TIMEOUT β€” the server normally times out an idle cursor after an inactivity period (10 minutes). this flag prevents that. lowkey a lifesaver.
  • MONGOC_QUERY_AWAIT_DATA β€” use with MONGOC_QUERY_TAILBLE_CURSOR... wait no, MONGOC_QUERY_TAILABLE_CURSOR. it blocks rather than returning no data, and after a period it times out.
  • MONGOC_QUERY_EXHAUST β€” unused. that's it. unused. πŸ’€
  • MONGOC_QUERY_PARTIAL β€” get partial results from mongos if some shards are down, instead of throwing an error. imperfect but slaying anyway ✨

mongoc_rand

MongoDB Random Number Generator 🎲

Synopsis

void
mongoc_rand_add (const void *buf, int num, double entropy);

void
mongoc_rand_seed (const void *buf, int num);

int
mongoc_rand_status (void);

Description

The mongoc_rand family of functions gives you access to the low level randomness primitives that the MongoDB C Driver uses. specifically? they control the creation of cryptographically strong pseudo-random bytes, which some security mechanisms literally require. so yeah, kind of a big deal πŸ‘‘

We can usually pull enough entropy from the environment, but depending on your OS, your hardware, and whatever other entropy consumers are running on the same system, you may be required to seed the PRNG manually. so like, sometimes you gotta help a girl out.

Entropy

mongoc_rand_add and mongoc_rand_seed let the user directly provide entropy. the difference is that mongoc_rand_seed requires that each bit provided is fully random, whereas mongoc_rand_add also lets you specify the degree of randomness in the bytes you're handing over. so add is the chill one and seed is the strict one, no cap.

Status

mongoc_rand_status lets you check the status of the mongoc PRNG. use it to guarantee sufficient entropy at program startup instead of waiting around for runtime errors to show up and ruin your whole day 😭 proactive queen behaviour fr fr.


mongoc_read_concern_t

Read Concern abstraction πŸ’…

Synopsis

New in MongoDB 3.2. ✨

The mongoc_read_concern_t lets clients choose a level of isolation for their reads. the default, MONGOC_READ_CONCERN_LEVEL_LOCAL, is right for the great majority of applications. like, it's the main character for a reason.

You can specify a read concern on connection objects, database objects, or collection objects. flexible? yes. iconic? also yes.

See readConcern on the MongoDB website for more information.

Important vibe check: Read Concern is only sent to MongoDB when it has explicitly been set by mongoc_read_concern_set_level() to anything other than NULL. otherwise it's just sitting there at home not being sent anywhere 🫢

Read Concern Levels

  • MONGOC_READ_CONCERN_LEVEL_LOCAL β€” level "local", the default. first available in MongoDB 3.2.
  • MONGOC_READ_CONCERN_LEVEL_MAJORITY β€” level "majority". first available in MongoDB 3.2.
  • MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE β€” level "linearizable". first available in MongoDB 3.4.
  • MONGOC_READ_CONCERN_LEVEL_AVAILABLE β€” level "available". first available in MongoDB 3.6.
  • MONGOC_READ_CONCERN_LEVEL_SNAPSHOT β€” level "snapshot". first available in MongoDB 4.0.

For the sake of compatibility with future versions of MongoDB, mongoc_read_concern_set_level() allows any string, not just this list of known read concern levels. so like, it's not gonna gatekeep you πŸ¦‹

See Read Concern Levels in the MongoDB manual for more information about the individual read concern levels.


mongoc_read_mode_t

Read Preference Modes 🌈

Synopsis

typedef enum {
   MONGOC_READ_PRIMARY = (1 << 0),
   MONGOC_READ_SECONDARY = (1 << 1),
   MONGOC_READ_PRIMARY_PREFERRED = (1 << 2) | MONGOC_READ_PRIMARY,
   MONGOC_READ_SECONDARY_PREFERRED = (1 << 2) | MONGOC_READ_SECONDARY,
   MONGOC_READ_NEAREST = (1 << 3) | MONGOC_READ_SECONDARY,
} mongoc_read_mode_t;

Description

This enum describes how reads should be dispatched. the default is MONGOC_READ_PRIMARY. ✨

Please see the MongoDB website for a description of Read Preferences.


mongoc_read_prefs_t

A read preference abstraction πŸ’–

Synopsis

mongoc_read_prefs_t provides an abstraction on top of the MongoDB connection read preferences. it lets you hint to the driver which nodes in a replica set should be accessed first, and how. it's basically the driver's little gossip network 🐝

You can specify a read preference mode on connection objects, database objects, collection objects, or per-operation. generally, it makes the most sense to stick with the global default mode, MONGOC_READ_PRIMARY β€” like, all of the other modes come with caveats that won't be covered in great detail here, so proceed with caution bestie 😌

  • MONGOC_READ_PRIMARY β€” the default mode, bestie πŸ’… all operations read from the current replica set primary, periodt.
  • MONGOC_READ_SECONDARY β€” all operations read from among the nearest secondary members of the replica set πŸ¦‹
  • MONGOC_READ_PRIMARY_PREFERRED β€” in most situations operations read from the primary, but if it's unavailable, operations read from secondary members. it's giving "primary first, but we have a backup plan" ✨
  • MONGOC_READ_SECONDARY_PREFERRED β€” in most situations operations read from among the nearest secondary members, but if no secondaries are available, operations read from the primary πŸ”₯
  • MONGOC_READ_NEAREST β€” operations read from among the nearest members of the replica set, irrespective of the member's type πŸ‘‘

🏷️ Tag Sets

tag sets let you specify custom read preferences and write concerns so your application can target operations to specific members. iykyk πŸ’–

custom read preferences and write concerns evaluate tag sets in different ways, and this is the part everyone gets confused about:

  • read preferences consider the value of a tag when selecting a member to read from 🌸
  • write concerns ignore the value of a tag when selecting a member, except to consider whether or not the value is unique πŸ’€

you can specify tag sets with the following read preference modes:

  • primaryPreferred
  • secondary
  • secondaryPreferred
  • nearest

tags are not compatible with MONGOC_READ_PRIMARY and, in general, only apply when selecting a secondary member of a set for a read operation. but here's the cute exception: the nearest read mode, when combined with a tag set, will select the nearest member that matches the specified tag set, which may be a primary or secondary 🫢

tag sets are represented as a comma-separated list of colon-separated key-value pairs when provided as a connection string, e.g. dc:ny,rack:1 😌

to specify a list of tag sets, use multiple readPreferenceTags, e.g.

readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=

note the empty value for the last one β€” that means "match any secondary as a last resort" 🧚 and yes, order matters when using multiple readPreferenceTags. don't play with it πŸ™ˆ

tag sets can also be configured using mongoc_read_prefs_set_tags() ✨

all interfaces use the same member selection logic to choose the member to which to direct read operations, basing the choice on read preference mode and tag sets. so like, no matter which door you come in through, same brain, same decision πŸ’œ


⏳ Max Staleness

when connected to a replica set running MongoDB 3.4 or later, the driver estimates the staleness of each secondary based on lastWriteDate values provided in server hello responses πŸ‘€

Max Staleness is the maximum replication lag in seconds (wall clock time) that a secondary can suffer and still be eligible for reads. the default is MONGOC_NO_MAX_STALENESS, which disables staleness checks entirely πŸŽ€ otherwise, it must be a positive integer at least MONGOC_SMALLEST_MAX_STALENESS_SECONDS (90 seconds). no cap, you can't go lower than that πŸ’…

max staleness is also supported by sharded clusters of replica sets if all servers run MongoDB 3.4 or later 🌈


πŸ¦” Hedged Reads

deprecated since version MongoDB: Server 8.0 😭 hedged reads are deprecated in MongoDB version 8.0 and will be removed in a future release. so like, enjoy them while they last, bestie πŸ’€

when connecting to a sharded cluster running MongoDB 4.4 or later, reads can be sent in parallel to the two "best" hosts. once one result returns, any other outstanding operations that were part of the hedged read are cancelled πŸ¦‹

when the read preference mode is MONGOC_READ_NEAREST and the sharded cluster is running MongoDB 4.4 or later, hedged reads are enabled by default ⭐ additionally, hedged reads may be explicitly enabled or disabled by calling mongoc_read_prefs_set_hedge() with a BSON document, e.g.

{
   enabled: true
}

appropriate values for the enabled key are true or false πŸŽ€


πŸ—‘οΈ mongoc_remove_flags_t

flags for deletion operations. yes, we're talking about removing things. icon behavior πŸ’…

Synopsis

typedef enum {
   MONGOC_REMOVE_NONE = 0,
   MONGOC_REMOVE_SINGLE_REMOVE = 1 << 0,
} mongoc_remove_flags_t;

Description

these flags correspond to the MongoDB wire protocol. they may be bitwise or'd together πŸ”₯ and lowkey they may change the number of documents that are removed during a remove command, so like… pay attention πŸ’€

Flag Values

  • MONGOC_REMOVE_NONE β€” specify no removal flags. all matching documents will be removed 😌
  • MONGOC_REMOVE_SINGLE_REMOVE β€” only remove the first matching document from the selector 🎯

🎫 mongoc_server_api_t

a versioned API to use for connections. fancy ✨

Synopsis

used to specify which version of the MongoDB server's API to use for driver connections.

the server API type takes a mongoc_server_api_version_t. it can optionally be strict about the list of allowed commands in that API version, and can also optionally provide errors for deprecated commands in that API version πŸ‘‘

a mongoc_server_api_t can be set on a client, and will then be sent to MongoDB for most commands run using that client 🫢


πŸ”’ mongoc_server_api_version_t

a representation of server API version numbers πŸ’œ

Synopsis

used to specify which version of the MongoDB server's API to use for driver connections.

Supported API Versions

the driver currently supports the following MongoDB API versions:

  • MONGOC_SERVER_API_V1 β€” MongoDB version string "1" ⭐

πŸ–₯️ mongoc_server_description_t

server description. it's giving "who even is this server" energy πŸ‘€

Synopsis

#include <mongoc/mongoc.h>
typedef struct _mongoc_server_description_t mongoc_server_description_t

mongoc_server_description_t holds information about a mongod or mongos the driver is connected to πŸ¦‹

Lifecycle

clean up a mongoc_server_description_t with mongoc_server_description_destroy() when necessary 🧹 literally don't leave it lying around, bestie πŸ’…

Applications receive a temporary reference to a mongoc_server_description_t as a parameter to an SDAM Monitoring callback β€” and that reference must not be destroyed. Like, do not touch it, bestie. See Introduction to Application Performance Monitoring. ✨

SEE ALSO 🫢

  • mongoc_client_get_server_descriptions()

πŸ’– mongoc_session_opt_t

#include <mongoc/mongoc.h>

typedef struct _mongoc_session_opt_t mongoc_session_opt_t;

Synopsis

okay so you start a session with mongoc_client_start_session(), use that session for a sequence of operations and multi-document transactions, then free it with mongoc_client_session_destroy(). Any mongoc_cursor_t or mongoc_change_stream_t using a session must be destroyed before the session, and a session must be destroyed before the mongoc_client_t it came from. That order is not optional. 🫢

By default, sessions are causally consistent. To disable causal consistency, before starting a session create a mongoc_session_opt_t with mongoc_session_opts_new() and call mongoc_session_opts_set_causal_consistency(), then free the struct with mongoc_session_opts_destroy().

Unacknowledged writes are prohibited with sessions.

A mongoc_client_session_t must be used by only one thread at a time. Due to session pooling, mongoc_client_start_session() may return a session that has been idle for some time and is about to be closed after its idle timeout. Use the session within one minute of acquiring it to refresh the session and avoid a timeout.

See the example code for mongoc_session_opts_set_causal_consistency().


🧦 mongoc_socket_t

Portable socket abstraction

Synopsis πŸ’«

#include <mongoc/mongoc.h>

typedef struct _mongoc_socket_t mongoc_socket_t

Synopsis 🫧

This structure provides a socket abstraction that is friendlier for portability than BSD sockets directly. Inconsistencies between Linux, various BSDs, Solaris, and Windows are handled here.


πŸ” mongoc_ssl_opt_t

Synopsis

typedef struct {
   const char *pem_file;
   const char *pem_pwd;
   const char *ca_file;
   const char *ca_dir;
   const char *crl_file;
   bool weak_cert_validation;
   bool allow_invalid_hostname;
   void *internal;
   void *padding[6];
} mongoc_ssl_opt_t;
NOTE: Though some API names include the term "ssl", the C driver only support TLS protocols, which supersede SSL. That's the tea. πŸ«–

Description

This structure is used to set the TLS options for a mongoc_client_t or mongoc_client_pool_t.

Beginning in version 1.2.0, once a pool or client has any TLS options set, all connections use TLS, even if ssl=true is omitted from the MongoDB URI. Before, TLS options were ignored unless tls=true was included in the URI.

As of 1.4.0, the mongoc_client_pool_set_ssl_opts() and mongoc_client_set_ssl_opts() will not only shallow copy the struct, but will also copy the const char*. It is therefore no longer needed to make sure the values remain valid after setting them.

SEE ALSO 🌈

  • Configuring TLS
  • mongoc_client_set_ssl_opts()
  • mongoc_client_pool_set_ssl_opts()

πŸ¦‹ mongoc_stream_buffered_t

Synopsis

typedef struct _mongoc_stream_buffered_t mongoc_stream_buffered_t;

Description

mongoc_stream_buffered_t should be considered a subclass of mongoc_stream_t. It performs buffering on an underlying stream.

SEE ALSO ✨

  • mongoc_stream_buffered_new()
  • mongoc_stream_destroy()

πŸŽ€ mongoc_stream_file_t

Synopsis

typedef struct _mongoc_stream_file_t mongoc_stream_file_t

mongoc_stream_file_t is a mongoc_stream_t subclass for working with standard UNIX style file-descriptors.


🧚 mongoc_stream_socket_t

Synopsis

typedef struct _mongoc_stream_socket_t mongoc_stream_socket_t

mongoc_stream_socket_t should be considered a subclass of mongoc_stream_t that works upon socket streams.


🌸 mongoc_stream_t

Synopsis

typedef struct _mongoc_stream_t mongoc_stream_t

mongoc_stream_t provides a generic streaming IO abstraction based on a struct of pointers interface. The idea is to allow wrappers, perhaps other language drivers, to easily shim their IO system on top of mongoc_stream_t.

The API for the stream abstraction is currently private and non-extensible.

Stream Types 🌊

There are a number of built in stream types that come with mongoc. The default configuration is a buffered unix stream. If TLS is in use, that in turn is wrapped in a tls stream.

SEE ALSO πŸ’œ

  • mongoc_stream_buffered_t
  • mongoc_stream_file_t
  • mongoc_stream_socket_t
  • mongoc_stream_tls_t

πŸ“ mongoc_stream_tls_t

Synopsis

typedef struct _mongoc_stream_tls_t mongoc_stream_tls_t

mongoc_stream_tls_t is a mongoc_stream_t subclass for working with TLS streams.


πŸ‘‘ mongoc_topology_description_t

Status of MongoDB Servers

Synopsis

typedef struct _mongoc_topology_description_t mongoc_topology_description_t;

mongoc_topology_description_t is an opaque type representing the driver's knowledge of the MongoDB server or servers it is connected to. Its API conforms to the SDAM Monitoring Specification.

Applications receive a temporary reference to a mongoc_topology_description_t as a parameter to an SDAM Monitoring callback that must not be destroyed. See Introduction to Application Performance Monitoring.


πŸ’… mongoc_transaction_opt_t

#include <mongoc/mongoc.h>

typedef struct _mongoc_transaction_opt_t mongoc_transaction_opt_t;

Synopsis

Options for starting a multi-document transaction.

When a session is first created with mongoc_client_start_session(), it inherits from the client the read concern, write concern, and read preference with which to start transactions. Each of these fields can be overridden independently. Create a mongoc_transaction_opt_t with mongoc_transaction_opts_new(), and pass a non-NULL option to any of the mongoc_transaction_opt_t setter functions:

  • mongoc_transaction_opts_set_read_concern()
  • mongoc_transaction_opts_set_write_concern()
  • mongoc_transaction_opts_set_read_prefs()

Pass the resulting transaction options to mongoc_client_session_start_transaction(). Each field set in the transaction options overrides the inherited client configuration.

Example 🎬

example-transaction.c

/* gcc example-transaction.c -o example-transaction \
 *     $(pkg-config --cflags --libs libmongoc-1.0) */

/* ./example-transaction [CONNECTION_STRING] */

#include <mongoc/mongoc.h>

#include <stdio.h>

int
main(int argc, char *argv[])
{
   int exit_code = EXIT_FAILURE;

   mongoc_client_t *client = NULL;
   mongoc_database_t *database = NULL;
   mongoc_collection_t *collection = NULL;
   mongoc_client_session_t *session = NULL;
   mongoc_session_opt_t *session_opts = NULL;
   mongoc_transaction_opt_t *default_txn_opts = NULL;
   mongoc_transaction_opt_t *txn_opts = NULL;
   mongoc_read_concern_t *read_concern = NULL;
   mongoc_write_concern_t *write_concern = NULL;
   const char *uri_string = "mongodb://127.0.0.1/?appname=transaction-example";
   mongoc_uri_t *uri;
   bson_error_t error;
   bson_t *doc = NULL;
   bson_t *insert_opts = NULL;
   int32_t i;
   int64_t start;
   bson_t reply = BSON_INITIALIZER;
   char *reply_json;
   bool r;

   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:\n"
              "error message: %s\n",
              error.message);
      goto done;
   }

   client = mongoc_client_new_from_uri(uri);
   if (!client) {
      goto done;
   }

   mongoc_client_set_error_api(client, 2);
   database = mongoc_client_get_database(client, "example-transaction");

   /* inserting into a nonexistent collection normally creates it, but a
    * collection can't be created in a transaction; create it now */
   collection = mongoc_database_create_collection(database, "collection", NULL, &error);

   if (!collection) {
      /* code 48 is NamespaceExists, see error_codes.err in mongodb source */
      if (error.code == 48) {
         collection = mongoc_database_get_collection(database, "collection");
      } else {
         fprintf(stderr, "Failed to create collection: %s\n", error.message);
         goto done;
      }
   }

   /* a transaction's read preferences, read concern, and write concern can be
    * set on the client, on the default transaction options, or when starting
    * the transaction. for the sake of this example, set read concern on the
    * default transaction options. */
   default_txn_opts = mongoc_transaction_opts_new();
   read_concern = mongoc_read_concern_new();
   mongoc_read_concern_set_level(read_concern, "snapshot");
   mongoc_transaction_opts_set_read_concern(default_txn_opts, read_concern);
   session_opts = mongoc_session_opts_new();
   mongoc_session_opts_set_default_transaction_opts(session_opts, default_txn_opts);

   session = mongoc_client_start_session(client, session_opts, &error);
   if (!session) {
      fprintf(stderr, "Failed to start session: %s\n", error.message);
      goto done;
   }

   /* in this example, set write concern when starting the transaction */
   txn_opts = mongoc_transaction_opts_new();
   write_concern = mongoc_write_concern_new();
   mongoc_write_concern_set_wmajority(write_concern, 1000 /* wtimeout */);
   mongoc_transaction_opts_set_write_concern(txn_opts, write_concern);

   insert_opts = bson_new();
   if (!mongoc_client_session_append(session, insert_opts, &error)) {
      fprintf(stderr, "Could not add session to opts: %s\n", error.message);
      goto done;
   }

retry_transaction:
   r = mongoc_client_session_start_transaction(session, txn_opts, &error);
   if (!r) {
      fprintf(stderr, "Failed to start transaction: %s\n", error.message);
      goto done;
   }

   /* insert two documents - on error, retry the whole transaction */
   for (i = 0; i < 2; i++) {
      doc = BCON_NEW("_id", BCON_INT32(i));
      bson_destroy(&reply);
      r = mongoc_collection_insert_one(collection, doc, insert_opts, &reply, &error);

      bson_destroy(doc);

      if (!r) {
         fprintf(stderr, "Insert failed: %s\n", error.message);
         mongoc_client_session_abort_transaction(session, NULL);
             /* a network error, primary failover, or other temporary error in a
              * transaction includes {"errorLabels": ["TransientTransactionError"]},
              * meaning that trying the entire transaction again may succeed
              */
             if (mongoc_error_has_label(&reply, "TransientTransactionError")) {
                goto retry_transaction;
             }

             goto done;
          }

          reply_json = bson_as_relaxed_extended_json(&reply, NULL);
          printf("%s\n", reply_json);
          bson_free(reply_json);
       }

       /* in case of transient errors, retry for 5 seconds to commit transaction */
       start = bson_get_monotonic_time();
       while (bson_get_monotonic_time() - start < 5 * 1000 * 1000) {
          bson_destroy(&reply);
          r = mongoc_client_session_commit_transaction(session, &reply, &error);
          if (r) {
             /* success */
             break;
          } else {
             fprintf(stderr, "Warning: commit failed: %s\n", error.message);
             if (mongoc_error_has_label(&reply, "TransientTransactionError")) {
                goto retry_transaction;
             } else if (mongoc_error_has_label(&reply, "UnknownTransactionCommitResult")) {
                /* try again to commit */
                continue;
             }

             /* unrecoverable error trying to commit */
             break;
          }
       }

       exit_code = EXIT_SUCCESS;

    done:
       bson_destroy(&reply);
       bson_destroy(insert_opts);
       mongoc_write_concern_destroy(write_concern);
       mongoc_read_concern_destroy(read_concern);
       mongoc_transaction_opts_destroy(txn_opts);
       mongoc_transaction_opts_destroy(default_txn_opts);
       mongoc_client_session_destroy(session);
       mongoc_collection_destroy(collection);
       mongoc_database_destroy(database);
       mongoc_uri_destroy(uri);
       mongoc_client_destroy(client);

       mongoc_cleanup();

       return exit_code;
    }

🌸 mongoc_transaction_state_t 🌸

Literally the "where are we rn" enum for transactions β€” constants for transaction states, bestie πŸ’…

✨ Synopsis ✨

typedef enum {
  MONGOC_TRANSACTION_NONE = 0,
  MONGOC_TRANSACTION_STARTING = 1,
  MONGOC_TRANSACTION_IN_PROGRESS = 2,
  MONGOC_TRANSACTION_COMMITTED = 3,
  MONGOC_TRANSACTION_ABORTED = 4,
} mongoc_transaction_state_t;

🫢 Description 🫢

Okay so these constants describe the current transaction state of a session. That's the whole vibe check β€” where's your transaction at, babes?

πŸ‘‘ Flag Values πŸ‘‘

  • MONGOC_TRANSACTION_NONE β€” There is no transaction in progress. Nothing's happening, we're chillin' 😌
  • MONGOC_TRANSACTION_STARTING β€” A transaction has been started, but no operation has been sent to the server. Like, the group chat is made but nobody's typed yet 😭
  • MONGOC_TRANSACTION_IN_PROGRESS β€” A transaction is in progress. Main character energy, it's happening πŸ”₯
  • MONGOC_TRANSACTION_COMMITTED β€” The transaction was committed. Slay, she's official πŸ’–
  • MONGOC_TRANSACTION_ABORTED β€” The transaction was aborted. Not me crying, it's fine, we move πŸ’€

πŸ¦‹ mongoc_update_flags_t πŸ¦‹

Flags for update operations β€” the little bit-flags that tell your update how to behave ✨

✨ Synopsis ✨

typedef enum {
   MONGOC_UPDATE_NONE = 0,
   MONGOC_UPDATE_UPSERT = 1 << 0,
   MONGOC_UPDATE_MULTI_UPDATE = 1 << 1,
} mongoc_update_flags_t;

#define MONGOC_UPDATE_NO_VALIDATE (1U << 31)

🫢 Description 🫢

These flags correspond to the MongoDB wire protocol. They may be bitwise or'd together β€” yes bestie, | is your bestie here fr fr. They let you modify the way an update is performed in the MongoDB server.

πŸ‘‘ Flag Values πŸ‘‘

  • MONGOC_UPDATE_NONE β€” No update flags set. Default vibes, zero notes πŸ™‚
  • MONGOC_UPDATE_UPSERT β€” If an upsert should be performed. aka "if she's not there, make her there" πŸ’…
  • MONGOC_UPDATE_MULTI_UPDATE β€” If more than a single matching document should be updated. By default only the first document is updated β€” so yeah, you gotta opt in to the "update everyone" life 😀
  • MONGOC_UPDATE_NO_VALIDATE β€” Do not perform client side BSON validations when performing an update. This is useful if you already know your BSON documents are valid. Highkey a flex for the confident girlies ⭐

🌈 mongoc_uri_t 🌈

✨ Synopsis ✨

typedef struct _mongoc_uri_t mongoc_uri_t;

🫢 Description 🫢

mongoc_uri_t provides an abstraction on top of the MongoDB connection URI format. It gives you standardized parsing plus convenience methods for extracting useful information such as replica hosts or authorization information. It's giving "glow-up for a string" πŸŽ€

See Connection String URI Reference on the MongoDB website for more information.

🧚 Format 🧚

mongodb[+srv]://                             <1>
   [username:password@]                      <2>
   host1                                     <3>
   [:port1]                                  <4>
   [,host2[:port2],...[,hostN[:portN]]]      <5>
   [/[database]                              <6>
   [?options]]                               <7>
  1. "mongodb" is the specifier of the MongoDB protocol. Use "mongodb+srv" with a single service name in place of "host1" to specify the initial list of servers with an SRV record. ✨
  2. An optional username and password. Optional! Like your crush's texts πŸ™ˆ
  3. The only required part of the uri. This specifies either a hostname, IPv4 address, IPv6 address enclosed in "[" and "]", or UNIX domain socket. The non-negotiable one πŸ‘‘
  4. An optional port number. Defaults to :27017.
  5. Extra optional hosts and ports. You would specify multiple hosts, for example, for connections to replica sets. The more the merrier 🫢
  6. The name of the database to authenticate if the connection string includes authentication credentials. If /database is not specified and the connection string includes credentials, defaults to the 'admin' database.
  7. Connection specific options. The sprinkle-on-top part πŸ“
NOTE: Option names are case-insensitive. Do not repeat the same option (e.g. "mongodb://localhost/db?opt=value1&OPT=value2") since this may have unexpected results. Fr fr, don't do it, it's not the move 😭

The MongoDB C Driver exposes constants for each supported connection option. These constants make it easier to discover connection options, but their string values can be used as well.

For example, the following calls are equal. Like, literally identical energy πŸ’–

uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_APPNAME "=applicationName");
uri = mongoc_uri_new ("mongodb://localhost/?appname=applicationName");
uri = mongoc_uri_new ("mongodb://localhost/?appName=applicationName");

🌸 Replica Set Example 🌸

To describe a connection to a replica set named 'test' with the following mongod hosts:

  • db1.example.com on port 27017
  • db2.example.com on port 2500

You would use a connection string that resembles the following. Iconic, no notes πŸ’…

mongodb://db1.example.com,db2.example.com:2500/?replicaSet=test

πŸ’œ SRV Example πŸ’œ

If you have configured an SRV record with a name like "_mongodb._tcp.server.example.com" whose records are a list of one or more MongoDB server hostnames, use a connection string like this:

uri = mongoc_uri_new ("mongodb+srv://server.example.com/?replicaSet=rs&appName=applicationName");

The driver prefixes the service name with "_mongodb._tcp.", then performs a DNS SRV query to resolve the service name to one or more hostnames. If this query succeeds, the driver performs a DNS TXT query on the service name (without the "_mongodb._tcp" prefix) for additional URI options configured as TXT records. She's doing research, okay? πŸ”

On Unix, the MongoDB C Driver relies on libresolv to look up SRV and TXT records. If libresolv is unavailable, then using a "mongodb+srv" URI will cause an error. If your libresolv lacks res_nsearch then the driver will fall back to res_search, which is not thread-safe. Yeah. Not the vibe, but forewarned is forearmed πŸ’€

Set the environment variable MONGOC_EXPERIMENTAL_SRV_PREFER_TCP to prefer TCP for the initial queries. The environment variable is ignored for res_search. Large DNS responses over UDP may be truncated due to UDP size limitations. DNS resolvers are expected to retry over TCP if the UDP response indicates truncation. Some observed DNS environments do not set the truncation flag (TC), preventing the TCP retry. This environment variable is currently experimental and subject to change β€” so like, don't get too attached 🫢

🌐 IPv4 and IPv6

Okay so this is the part where DNS gets messy, bestie, listen up. If you're connecting to a hostname that has both IPv4 and IPv6 DNS records, the behavior follows RFC-6555. A connection to the IPv6 address is attempted first. If IPv6 fails, then a connection is attempted to the IPv4 address. And here's the spicy bit: if the connection attempt to IPv6 does not complete within 250ms, then IPv4 is tried in parallel. Whichever succeeds connection first cancels the other. The successful DNS result is cached for 10 minutes. ✨

As a consequence, attempts to connect to a mongod only listening on IPv4 may be delayed if there are both A (IPv4) and AAAA (IPv6) DNS records associated with the host. 😭

To avoid a delay, configure hostnames to match the MongoDB configuration. That is, only create an A record if the mongod is only listening on IPv4. Do that and you're slaying, fr fr 🫢

πŸ”Œ Connection Options

This is the big glow-up table of connection options β€” every constant, its key, its default, and what it actually does. Buckle up, there's a bunch. πŸ’…

  • MONGOC_URI_RETRYREADS (retryreads) β€” default: true. If "true" and the server is a MongoDB 3.6+ standalone, replica set, or sharded cluster, the driver safely retries a read that failed due to a network error or replica set failover. 🩹
  • MONGOC_URI_RETRYWRITES (retrywrites) β€” default: true if driver built w/ TLS. If "true" and the server is a MongoDB 3.6+ replica set or sharded cluster, the driver safely retries a write that failed due to a network error or replica set failover. Only inserts, updates of single documents, or deletes of single documents are retried. πŸ‘‘
  • MONGOC_URI_MAXADAPTIVERETRIES (maxadaptiveretries) β€” default: 2. The maximum number of times the driver retries an operation that fails with a SystemOverloadedError. Must be a non-negative integer. This option works with MongoDB Atlas Server Version 9.0 and above. πŸ”
  • MONGOC_URI_ENABLEOVERLOADRETARGETING (enableoverloadretargeting) β€” default: false. If "true", the driver deprioritizes servers which returned a SystemOverloadedError when selecting a server to retry an operation. This option works with MongoDB Atlas Server Version 9.0 and above. 🎯
  • MONGOC_URI_APPNAME (appname) β€” default: Empty (no appname). The client application name. This value is used by MongoDB when it logs connection information and profile information, such as slow queries. 🌸
  • MONGOC_URI_TLS (tls) β€” default: Empty (not set, same as false). {true|false}, indicating if TLS must be used. (See also mongoc_client_set_ssl_opts() and mongoc_client_pool_set_ssl_opts().) πŸ”
  • MONGOC_URI_COMPRESSORS (compressors) β€” default: Empty (no compressors). Comma separated list of compressors, if any, to use to compress the wire protocol messages. Snappy, zlib, and zstd are optional build time dependencies, and enable the "snappy", "zlib", and "zstd" values respectively. πŸ—œοΈ
  • MONGOC_URI_CONNECTTIMEOUTMS / connecttimeoutms β€” default is 10,000 ms (that's 10 seconds bestie ⏱️). This one applies to new server connections, and it also doubles as the socket timeout for server discovery and monitoring operations. multitasking queen πŸ’…
  • MONGOC_URI_SOCKETTIMEOUTMS / sockettimeoutms β€” default 300,000 ms (5 whole minutes, yes really 😌). It's the time in milliseconds the driver will attempt to send or receive on a socket before that attempt times out.
  • MONGOC_URI_REPLICASET / replicaset β€” default is empty (aka no replicaset, we're free agents πŸ¦‹). This is the name of the Replica Set the driver should connect to.
  • MONGOC_URI_ZLIBCOMPRESSIONLEVEL / zlibcompressionlevel β€” default -1. When MONGOC_URI_COMPRESSORS includes "zlib", this option configures the zlib compression level, used when the zlib compressor is compressing client data. tiny number, big job ✨
  • MONGOC_URI_LOADBALANCED / loadbalanced β€” default false. If it's true, that's the driver's way of saying "hey, I'm connecting to a MongoDB cluster behind a load balancer." πŸŽ€
  • MONGOC_URI_SRVMAXHOSTS / srvmaxhosts β€” default 0. If it's zero, the number of hosts in DNS results is unlimited (go off, infinite hosts 🌈). If it's greater than zero, the number of hosts in DNS results is limited to being less than or equal to the value you gave.

⚠️ WARNING: Setting any of the *timeoutMS options above to either 0 or a negative value is discouraged β€” the behavior is unspecified and inconsistent, and we do not stan chaos πŸ™ˆ. The "default value" that historically got specified as a fallback for 0 or a negative value is NOT related to the default values for the *timeoutMS options documented above, okay? The meaning of a timeout of 0 or a negative value may vary depending on the operation being executed β€” even when it's specified by the same URI option. literally wild πŸ’€. If you actually want the documented default value for a *timeoutMS option, use the MONGOC_DEFAULT_* constants defined in mongoc-client.h instead. periodt. πŸ’…

πŸ’– Authentication Options πŸ’–

  • MONGOC_URI_AUTHMECHANISM / authmechanism β€” specifies the mechanism to use when authenticating as the provided user. See Authentication for the supported values. πŸ”
  • MONGOC_URI_AUTHMECHANISMPROPERTIES / authmechanismproperties β€” extra properties for the mechanism you specified, in key-value pair format, like key1:value1,key2:value2. πŸŽ€
  • MONGOC_URI_AUTHSOURCE / authsource β€” the name of the database that authentication commands get sent to, or $external depending on the specified mechanism. It overrides the auth database in the URI when applicable. main character behavior honestly πŸ‘‘

πŸ’… Mechanism Properties

The following properties may be specified as key-value pairs for the MONGOC_URI_AUTHMECHANISMPROPERTIES option.

Invalid or unsupported properties may be reported as a client error when a corresponding authentication mechanism is also specified.

πŸ¦‹ MONGODB-OIDC

  • ENVIRONMENT β€” The name of a built-in OIDC provider integration. Must be one of ["azure", "gcp", "k8s"].
  • TOKEN_RESOURCE β€” The URI of the target resource. ENVIRONMENT must be one of ["azure", "gcp"].
⚠️ WARNING: A TOKEN_RESOURCE property value MUST NOT contain the comma character "," when specified as a connection string query option, even when percent-encoded. A value containing a comma character may be set using mongoc_uri_set_mechanism_properties() instead. However, the value MAY contain the colon character ":", as only the first colon is interpreted as a key-value delimiter.

✨ GSSAPI

  • SERVICE_NAME β€” Optional. Defaults to "mongodb".
  • CANONICALIZE_HOST_NAME β€” Optional. Must be one of ["false", "true"]. "false" performs no canonicalization (aka "none"). "true" performs a forward DNS lookup and then a reverse lookup on that value to canonicalize the hostname (aka "forwardAndReverse").
  • SERVICE_REALM β€” Optional. May be needed for cross-realm authentication where the user and service exist in different realms.
  • SERVICE_HOST β€” Optional. May be needed to use a service host that differs from the initial role.

πŸ’₯ MONGODB-AWS

  • AWS_SESSION_TOKEN β€” Optional. An AWS session token to use for authentication with temporary credentials.

🚫 Deprecated Mechanism Property Options

The following options have been deprecated and may be removed from future releases of libmongoc.

  • MONGOC_URI_CANONICALIZEHOSTNAME β€” constant whose key is canonicalizehostname. Deprecated for: MONGOC_URI_AUTHMECHANISMPROPERTIES, key authmechanismproperties (CANONICALIZE_HOST_NAME).
  • MONGOC_URI_GSSAPISERVICENAME β€” constant whose key is gssapiservicename. Deprecated for: MONGOC_URI_AUTHMECHANISMPROPERTIES, key authmechanismproperties (SERVICE_NAME).

πŸ” TLS Options

  • MONGOC_URI_TLS β€” constant whose key is tls. Description: {true|false}, indicating if TLS must be used.
  • MONGOC_URI_TLSCERTIFICATEKEYFILE β€” constant whose key is tlscertificatekeyfile. Description: Path to PEM formatted Private Key, with its Public Certificate concatenated at the end.
  • MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD β€” constant whose key is tlscertificatekeypassword. Description: The password, if any, to use to unlock encrypted Private Key.
  • MONGOC_URI_TLSCAFILE (tlscafile) β€” points at one Certificate Authority, or a whole bundle of them, that should be considered trusted. 🫢
  • MONGOC_URI_TLSALLOWINVALIDCERTIFICATES (tlsallowinvalidcertificates) β€” accept and ignore certificate verification errors (untrusted issuer, expired cert, etc.). It’s giving β€œbestie, are we sure?” energy. 😭
  • MONGOC_URI_TLSALLOWINVALIDHOSTNAMES (tlsallowinvalidhostnames) β€” ignore hostname verification of the certificate (like a Man In The Middle situation where the cert is valid but was issued for another hostname). πŸ’€
  • MONGOC_URI_TLSINSECURE (tlsinsecure) β€” takes {true|false}, indicating if insecure TLS options should be used. Currently this implies MONGOC_URI_TLSALLOWINVALIDCERTIFICATES and MONGOC_URI_TLSALLOWINVALIDHOSTNAMES. So yeah, it’s the β€œturn off the safety rails” option. 🚨
  • MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK (tlsdisablecertificaterevocationcheck) β€” takes {true|false}, indicating if revocation checking (CRL / OCSP) should be disabled. πŸ”₯
  • MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK (tlsdisableocspendpointcheck) β€” takes {true|false}, indicating if OCSP responder endpoints should not be requested when an OCSP response is not stapled. ✨
See Configuring TLS for details about these options and about building libmongoc with TLS support. πŸŽ€

πŸ’€ Deprecated SSL Options πŸ’€

The following options have been deprecated and may be removed from future releases of libmongoc. So like… use the new ones, bestie. πŸ™ˆ

  • MONGOC_URI_SSL (ssl) β€” deprecated for MONGOC_URI_TLS (tls).
  • MONGOC_URI_SSLCLIENTCERTIFICATEKEYFILE (sslclientcertificatekeyfile) β€” deprecated for MONGOC_URI_TLSCERTIFICATEKEYFILE (tlscertificatekeyfile).
  • MONGOC_URI_SSLCLIENTCERTIFICATEKEYPASSWORD (sslclientcertificatekeypassword) β€” deprecated for MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD (tlscertificatekeypassword).
  • MONGOC_URI_SSLCERTIFICATEAUTHORITYFILE (sslcertificateauthorityfile) β€” deprecated for MONGOC_URI_TLSCAFILE (tlscafile).
  • MONGOC_URI_SSLALLOWINVALIDCERTIFICATES (sslallowinvalidcertificates) β€” deprecated for MONGOC_URI_TLSALLOWINVALIDCERTIFICATES (tlsallowinvalidcertificates).
  • MONGOC_URI_SSLALLOWINVALIDHOSTNAMES β€” key sslallowinvalidhostnames β€” and this is the older name's modern glow-up: MONGOC_URI_TLSALLOWINVALIDHOSTNAMES with key tlsallowinvalidhostnames πŸ’«

🌐 Server Discovery, Monitoring, and Selection Options

Okay so this is the whole saga of how the driver goes out and finds your servers and then picks one, and honestly there's a lot happening behind the scenes, so let's get into it 🫢

  • Clients inside a mongoc_client_pool_t share a topology scanner, and that scanner lives on a background thread. The thread wakes up every heartbeatFrequencyMS (default 10 seconds) and scans all the MongoDB servers it knows about, in parallel. Multi-tasking icon behaviour, honestly ✨
  • Now, any time an application operation needs a server that isn't known yet β€” like if there's no known primary and your app tries an insert β€” that thread rescans all the servers every half-second. While that's going on, the pooled client waits up to serverSelectionTimeoutMS (default 30 seconds) for the thread to find a server that actually suits the operation, and then it returns an error with domain MONGOC_ERROR_SERVER_SELECTION 😭 it tried its best.
  • Technically β€” nerd glasses on πŸ‘“ β€” the total amount of time an operation may wait while a pooled client scans the topology is controlled by both serverSelectionTimeoutMS and connectTimeoutMS. The absolute longest wait happens if the last scan begins right at the end of the selection timeout and a slow or down server needs the full connection timeout before the client finally gives up. That's the worst-case-scenario combo meal right there πŸ’€
  • A non-pooled client is single-threaded, bestie. Every heartbeatFrequencyMS it just blocks the next application operation while it does a parallel scan. And that scan takes as long as it needs to check the slowest server β€” roughly connectTimeoutMS. Which is precisely why the default heartbeatFrequencyMS for single-threaded clients is bigger than for pooled clients: 60 seconds instead of 10. respectful of your time, we love to see it πŸ’…
  • By default, single-threaded (non-pooled) clients scan only once when an operation needs a server it doesn't know about. So if you attempt an insert and there's no known primary, the client checks all the servers one time trying to find it, then either succeeds or returns an error with domain MONGOC_ERROR_SERVER_SELECTION. But! If you set serverSelectionTryOnce to "false", the single-threaded client loops, checking all servers every half-second, until serverSelectionTimeoutMS expires. committed to the bit 🫑
  • The total time an operation may wait for a single-threaded client to scan the topology is determined by connectTimeoutMS in the try-once case, or by serverSelectionTimeoutMS and connectTimeoutMS if serverSelectionTryOnce is set to "false".

πŸŽ€ The Constants (and their keys)

  • MONGOC_URI_HEARTBEATFREQUENCYMS β€” key heartbeatfrequencyms β€” the interval between server monitoring checks. Defaults to 10,000ms (10 seconds) in pooled (multi-threaded) mode, and 60,000ms (60 seconds) in non-pooled mode (single-threaded). ⏰ it's giving different defaults for different lifestyles.
  • MONGOC_URI_SERVERSELECTIONTIMEOUTMS β€” key serverselectiontimeoutms β€” a timeout in milliseconds to block for server selection before throwing an exception. The default is 30,0000ms (30 seconds). And yes, that comma is literally written like that in the source β€” we are not fixing it, we are respecting it 😭 it means 30 seconds, bestie, don't panic.
  • MONGOC_URI_SERVERSELECTIONTRYONCE β€” key serverselectiontryonce β€” if "true", the driver scans the topology exactly once after server selection fails, then either selects a server or returns an error. If it's "false", the driver searches again and again for a suitable server for up to serverSelectionTimeoutMS milliseconds, pausing half a second between attempts. The default for serverSelectionTryOnce is "false" for pooled clients, otherwise "true". And plot twist: pooled clients ignore serverSelectionTryOnce entirely β€” instead they signal the thread to rescan the topology every half-second until serverSelectionTimeoutMS expires. main character energy, refusing to follow the rules πŸ’«
  • MONGOC_URI_SOCKETCHECKINTERVALMS β€” key socketcheckintervalms β€” only applies to single threaded clients. If a socket hasn't been used within this amount of time, its connection gets checked with a quick "hello" call before it's used again. Defaults to 5,000ms (5 seconds). just a little wellness check before we get back to business πŸ‘‹
  • MONGOC_URI_DIRECTCONNECTION β€” key directconnection β€” if "true", the driver connects to a single server directly and will not monitor any additional servers. If "false", the driver connects based on the presence and value of the replicaSet option. pick a lane, but make it a documented one 🎯
πŸ’– PSA bestie: setting any of the *TimeoutMS options above to 0 is gonna be interpreted as "use the default value". Not zero. Default. Don't @ me, that's just how she works. ✨

πŸŠβ€β™€οΈ Connection Pool Options πŸŠβ€β™€οΈ

Okay so these options are the ones that govern the behavior of a mongoc_client_pool_t. Heads up tho: a non-pooled mongoc_client_t ignores them completely β€” like, doesn't even look. πŸ™ˆ

  • MONGOC_URI_MAXPOOLSIZE, key maxpoolsize β€” the maximum number of clients created by a mongoc_client_pool_t total (both the ones sitting in the pool and the ones checked out). The default value is 100. And once you hit that ceiling? mongoc_client_pool_pop() just blocks until another thread pushes a client back. No cap, you're waiting. πŸ’€
  • MONGOC_URI_WAITQUEUETIMEOUTMS, key waitqueuetimeoutms β€” the maximum time to wait for a client to become available from the pool. ⏳

✍️ Write Concern Options ✍️

  • MONGOC_URI_W, key w β€” determines the write concern (aka the guarantee, the "did it actually happen tho" factor). Valid values:
    • 0 β€” the driver will not acknowledge write operations, but it will pass or handle any network and socket errors that it receives to the client. 🫢 And if you disable write concern but enable the getLastError command's w option, w overrides the w option. (Yes, that's real, that's what it says.)
    • 1 β€” provides basic acknowledgement of write operations. By specifying 1, you require that a standalone mongod instance, or the primary for replica sets, acknowledge all write operations. For drivers released after the default write concern change, this is the default write concern setting. πŸ‘‘
    • majority β€” for replica sets, if you specify the special majority value to the w option, write operations will only return successfully after a majority of the configured replica set members have acknowledged the write operation. Like the group chat all reading your message before it counts as delivered. πŸ’…
  • n β€” for replica sets, if you specify a number n greater than 1, operations with this write concern return only after n members of the set have acknowledged the write. Heads up tho 🫢 if you set n to a number that is greater than the number of available set members or members that hold data, MongoDB will wait β€” and we mean wait β€” potentially indefinitely, for these members to become available. Like, it will just sit there. Patiently. Forever. πŸ’€
    • tags β€” for replica sets, you can specify a tag set to require that all members of the set that have these tags configured return confirmation of the write operation. cute, tagged, accountable ✨

  • MONGOC_URI_WTIMEOUTMS, wtimeoutms β€” the time in milliseconds to wait for replication to succeed, as specified in the w option, before timing out. And when wtimeoutMS is 0, write operations will never time out. never ever. no cap. πŸ‘‘
  • MONGOC_URI_JOURNAL, journal β€” controls whether write operations will wait until the mongod acknowledges the write operations and commits the data to the on disk journal. πŸ—‚οΈ
    • true β€” enables journal commit acknowledgement write concern. Equivalent to specifying the getLastError command with the j option enabled.
    • false β€” does not require that mongod commit write operations to the journal before acknowledging the write operation. This is the default option for the journal parameter. so yeah, that's the vibe out of the box πŸ™ˆ

🌸 Read Concern Options 🌸

  • MONGOC_URI_READCONCERNLEVEL, readconcernlevel β€” the level of isolation for read operations. If the level is left unspecified, the server default will be used. See readConcern in the MongoDB Manual for details. iykyk, the manual's got the lore πŸ“–

πŸ¦‹ Read Preference Options πŸ¦‹

When connected to a replica set, the driver chooses which member to query using the read preference:

  1. Choose members whose type matches readPreference. 🎯
  2. From these, if there are any tags sets configured, choose members matching the first tag set. If there are none, fall back to the next tag set and so on, until some members are chosen or the tag sets are exhausted. it's giving "keep swiping till you find the one" πŸ’…
  3. From the chosen servers, distribute queries randomly among the server with the fastest round-trip times. These include the server with the fastest time and any whose round-trip time is no more than localThresholdMS slower. ⚑ fastest besties only, but the near-fastest get to hang too

okay so next up it's the constants table, and it kicks off with Constant, Key, Description β€” stay tuned bestie, the good stuff's coming πŸŽ€

  • MONGOC_URI_READPREFERENCE, key readpreference β€” tells the driver which replica set read preference this connection rolls with. Fr fr this one overrides any secondaryOk value you set, so it's the main character here. The read preference values are literally these:
    1. primary (the default, bestie ✨)
    2. primaryPreferred
    3. secondary
    4. secondaryPreferred
    5. nearest
  • MONGOC_URI_READPREFERENCETAGS, key readpreferencetags β€” a representation of a tag set. Also see Tag Sets, iykyk πŸ’…
  • MONGOC_URI_LOCALTHRESHOLDMS, key localthresholdms β€” how far to distribute queries, beyond the server with the fastest round-trip time. By default, only servers within 15ms of the fastest round-trip time receive queries πŸŽ€
  • MONGOC_URI_MAXSTALENESSSECONDS, key maxstalenessseconds β€” the maximum replication lag, in wall clock time, that a secondary can suffer and still be eligible. Heads up: the smallest allowed value for maxStalenessSeconds is 90 seconds ⏱️
NOTE: when connecting to more than one mongos, libmongoc's localThresholdMS applies only to the selection of mongos servers. The threshold for selecting among replica set members in shards is controlled by the mongos's localThreshold command line option. Not me being specific about which threshold, but yes, they're different ones πŸ™ˆ

πŸ•°οΈ Legacy Options

For historical reasons, the following options are available. They should however not be used β€” like, they're giving deprecated, leave them in the past bestie πŸ’€

  • MONGOC_URI_SAFE, key safe β€” {true|false} Same as w={1|0}

πŸ” Version Checks

Conditional compilation based on mongoc version β€” so you can vibe-check the library before you compile against it πŸ¦‹

Description

The following preprocessor macros can be used to perform various checks based on the version of the library you are compiling against. This may be useful if you only want to enable a feature on a certain version of the library.

#include <mongoc/mongoc.h>

#define MONGOC_MAJOR_VERSION (x)
#define MONGOC_MINOR_VERSION (y)
#define MONGOC_MICRO_VERSION (z)
#define MONGOC_VERSION_S     "x.y.z"
#define MONGOC_VERSION_HEX   ((1 << 24) | (0 << 16) | (0 << 8) | 0)
#define MONGOC_CHECK_VERSION(major, minor, micro)

Only compile a block on MongoDB C Driver 1.1.0 and newer β€” iconic gatekeeping tbh:

#if MONGOC_CHECK_VERSION(1, 1, 0)
static void
do_something (void)
{
}
#endif

πŸ‘‘ mongoc_write_concern_t

The Write Concern abstraction. Absolutely essential, no cap πŸ’–

Synopsis

mongoc_write_concern_t tells the driver what level of acknowledgement to await from the server. The default, MONGOC_WRITE_CONCERN_W_DEFAULT, is right for the great majority of applications β€” so if that's you, congrats, you can literally just leave it alone ✨

You can specify a write concern on connection objects, database objects, collection objects, or per-operation. Data-modifying operations typically use the write concern of the object they operate on, and check the server response for a write concern error or write concern timeout. For example, mongoc_collection_drop_index() uses the collection's write concern, and a write concern error or timeout in the response is considered a failure 😭

Exceptions to this principle are the generic command functions β€” these ones do not play by that rule:

  • mongoc_client_command_simple()
  • mongoc_database_command_simple()
  • mongoc_collection_command_simple()

These generic command functions do not automatically apply a write concern, and they do not check the server response for a write concern error or write concern timeout. So like, you gotta handle that yourself, bestie 🫢

See Write Concern on the MongoDB website for more information 🌈

πŸŽ€ Write Concern Levels πŸŽ€

okay bestie, this is the dial that controls how much reassurance you want from the server that your write actually landed. You set it with mongoc_write_concern_set_w() and here's the whole menu:

  • MONGOC_WRITE_CONCERN_W_DEFAULT (1) β€” the vibe you get if you don't touch anything. By default, writes block awaiting acknowledgement from MongoDB. Acknowledged write concern is literally the reason clients can catch network errors, duplicate key errors, and other errors β€” it's giving safety net, and we respect it πŸ’…
  • MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED (0) β€” with this write concern, MongoDB does not acknowledge the receipt of write operation. Unacknowledged is similar to errors ignored; however, mongoc attempts to receive and handle network errors when possible. so like… it's not fully ghosting you, but it's also not texting back fr 🫠
  • MONGOC_WRITE_CONCERN_W_MAJORITY (majority) β€” block until a write has been propagated to a majority of the nodes in the replica set. crowd-pleaser behaviour, honestly πŸ‘‘
  • n β€” block until a write has been propagated to at least n nodes in the replica set. you pick the number, you set the stakes 🎯

πŸ¦‹ Application Performance Monitoring (APM) πŸ¦‹

The MongoDB C Driver allows you to monitor all the MongoDB operations the driver executes. This event-notification system conforms to two MongoDB driver specs β€” and yes, both of them are iconic in their own way:

  • Command Logging and Monitoring β€” events related to all application operations.
  • SDAM Monitoring β€” events related to the driver's Server Discovery And Monitoring logic.

To start receiving notifications, it's a three-step little ritual, no cap:

  1. Create a mongoc_apm_callbacks_t with mongoc_apm_callbacks_new()
  2. Set callbacks on it
  3. Pass it to mongoc_client_set_apm_callbacks() or mongoc_client_pool_set_apm_callbacks()

that's it. that's the whole thing. slay ✨


πŸ’œ Command-Monitoring Example πŸ’œ

file goes by example-command-monitoring.c and honestly she's a whole mood:

/* gcc example-command-monitoring.c -o example-command-monitoring \
 *     $(pkg-config --cflags --libs libmongoc-1.0) */

/* ./example-command-monitoring [CONNECTION_STRING] */

#include <mongoc/mongoc.h>

#include <stdio.h>

typedef struct {
   int started;
   int succeeded;
   int failed;
} stats_t;

void
command_started(const mongoc_apm_command_started_t *event)
{
   char *s;

   s = bson_as_relaxed_extended_json(mongoc_apm_command_started_get_command(event), NULL);
   printf("Command %s started on %s:\n%s\n\n",
          mongoc_apm_command_started_get_command_name(event),
          mongoc_apm_command_started_get_host(event)->host,
          s);

   ((stats_t *)mongoc_apm_command_started_get_context(event))->started++;

   bson_free(s);
}

void
command_succeeded(const mongoc_apm_command_succeeded_t *event)
{
   char *s;

   s = bson_as_relaxed_extended_json(mongoc_apm_command_succeeded_get_reply(event), NULL);
   printf("Command %s succeeded:\n%s\n\n", mongoc_apm_command_succeeded_get_command_name(event), s);

   ((stats_t *)mongoc_apm_command_succeeded_get_context(event))->succeeded++;

   bson_free(s);
}

void
command_failed(const mongoc_apm_command_failed_t *event)
{
   bson_error_t error;

   mongoc_apm_command_failed_get_error(event, &error);
   printf("Command %s failed:\n\"%s\"\n\n", mongoc_apm_command_failed_get_command_name(event), error.message);

   ((stats_t *)mongoc_apm_command_failed_get_context(event))->failed++;
}

int
main(int argc, char *argv[])
{
   mongoc_client_t *client;
   mongoc_apm_callbacks_t *callbacks;
   stats_t stats = {0};
   mongoc_collection_t *collection;
   bson_error_t error;
   const char *uri_string = "mongodb://127.0.0.1/?appname=cmd-monitoring-example";
   mongoc_uri_t *uri;
   const char *collection_name = "test";
   bson_t *docs[2];

   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:\n"
              "error message: %s\n",
              error.message);
      return EXIT_FAILURE;
   }

   client = mongoc_client_new_from_uri(uri);
   if (!client) {
      return EXIT_FAILURE;
   }

   mongoc_client_set_error_api(client, 2);
   callbacks = mongoc_apm_callbacks_new();
   mongoc_apm_set_command_started_cb(callbacks, command_started);
   mongoc_apm_set_command_succeeded_cb(callbacks, command_succeeded);
   mongoc_apm_set_command_failed_cb(callbacks, command_failed);
   mongoc_client_set_apm_callbacks(client, callbacks, (void *)&stats /* context pointer */);

   collection = mongoc_client_get_collection(client, "test", collection_name);
   mongoc_collection_drop(collection, NULL);

   docs[0] = BCON_NEW("_id", BCON_INT32(0));
   docs[1] = BCON_NEW("_id", BCON_INT32(1));
   mongoc_collection_insert_many(collection, (const bson_t **)docs, 2, NULL, NULL, NULL);

   /* duplicate key error on the second insert */
   mongoc_collection_insert_one(collection, docs[0], NULL, NULL, NULL);

   mongoc_collection_destroy(collection);
   mongoc_apm_callbacks_destroy(callbacks);
   mongoc_uri_destroy(uri);
   mongoc_client_destroy(client);

   printf("started: %d\nsucceeded: %d\nfailed: %d\n", stats.started, stats.succeeded, stats.failed);

   bson_destroy(docs[0]);
   bson_destroy(docs[1]);

   mongoc_cleanup();

   return EXIT_SUCCESS;
}

and this example program prints β€” brace yourself, it's a lot of lore:

Command drop started on 127.0.0.1:
{ "drop" : "test" }

Command drop succeeded:
{ "ns" : "test.test", "nIndexesWas" : 1, "ok" : 1.0 }

Command insert started on 127.0.0.1:
{
  "insert" : "test",
  "ordered" : true,
  "documents" : [
    { "_id" : 0 }, { "_id" : 1 }
  ]
}

Command insert succeeded:
{ "n" : 2, "ok" : 1.0 }

Command insert started on 127.0.0.1:
{
  "insert" : "test",
  "ordered" : true,
  "documents" : [
    { "_id" : 0 }
  ]
}

Command insert succeeded:
{
  "n" : 0,
  "writeErrors" : [
    { "index" : 0, "code" : 11000, "errmsg" : "duplicate key" }
  ],
  "ok" : 1.0
}

started: 3
succeeded: 3
failed: 0
heads up bestie: the output has been edited and formatted for clarity. Depending on your server configuration, messages may include metadata like database name, logical session ids, or cluster times that are not shown here. so don't come for me if yours looks extra πŸ’€

and the plot twist you need to understand: the final "insert" command is considered successful, despite the writeError, because the server replied to the overall command with "ok": 1. read that twice. it's giving "technically a win" energy 😭


🌈 SDAM Monitoring Example 🌈

next up, example-sdam-monitoring.c β€” the server-discovery bestie:

/* gcc example-sdam-monitoring.c -o example-sdam-monitoring \
 *     $(pkg-config --cflags --libs libmongoc-1.0) */

/* ./example-sdam-monitoring [CONNECTION_STRING] */

#include <mongoc/mongoc.h>

#include <stdio.h>

typedef struct {
   int server_changed_events;
   int server_opening_events;
   int server_closed_events;
   int topology_changed_events;
   int topology_opening_events;
   int topology_closed_events;
   int heartbeat_started_events;
   int heartbeat_succeeded_events;
   int heartbeat_failed_events;
} stats_t;

static void
server_changed(const mongoc_apm_server_changed_t *event)
{
   stats_t *context;
   const mongoc_server_description_t *prev_sd, *new_sd;

   context = (stats_t *)mongoc_apm_server_changed_get_context(event);
   context->server_changed_events++;

   prev_sd = mongoc_apm_server_changed_get_previous_description(event);
   new_sd = mongoc_apm_server_changed_get_new_description(event);

   printf("server changed: %s %s -> %s\n",
          mongoc_apm_server_changed_get_host(event)->host_and_port,
          mongoc_server_description_type(prev_sd),
          mongoc_server_description_type(new_sd));
}

static void
server_opening(const mongoc_apm_server_opening_t *event)
{
   stats_t *context;

   context = (stats_t *)mongoc_apm_server_opening_get_context(event);
   context->server_opening_events++;

   printf("server opening: %s\n", mongoc_apm_server_opening_get_host(event)->host_and_port);
}

static void
server_closed(const mongoc_apm_server_closed_t *event)
{
   stats_t *context;

   context = (stats_t *)mongoc_apm_server_closed_get_context(event);
   context->server_closed_events++;

   printf("server closed: %s\n", mongoc_apm_server_closed_get_host(event)->host_and_port);
}

okay bestie, buckle up, we're deep in the code mines now πŸ’Ž this is the rest of it and honestly it's giving main character energy β€” every callback, every print, verbatim, no cap:

static void
topology_changed(const mongoc_apm_topology_changed_t *event)
{
   stats_t *context;
   const mongoc_topology_description_t *prev_td;
   const mongoc_topology_description_t *new_td;
   mongoc_server_description_t **prev_sds;
   size_t n_prev_sds;
   mongoc_server_description_t **new_sds;
   size_t n_new_sds;
   size_t i;
   mongoc_read_prefs_t *prefs;

   context = (stats_t *)mongoc_apm_topology_changed_get_context(event);
   context->topology_changed_events++;

   prev_td = mongoc_apm_topology_changed_get_previous_description(event);
   prev_sds = mongoc_topology_description_get_servers(prev_td, &n_prev_sds);
   new_td = mongoc_apm_topology_changed_get_new_description(event);
   new_sds = mongoc_topology_description_get_servers(new_td, &n_new_sds);

   printf("topology changed: %s -> %s\n",
          mongoc_topology_description_type(prev_td),
          mongoc_topology_description_type(new_td));

   if (n_prev_sds) {
      printf("  previous servers:\n");
      for (i = 0; i < n_prev_sds; i++) {
         printf("      %s %s\n",
                mongoc_server_description_type(prev_sds[i]),
                mongoc_server_description_host(prev_sds[i])->host_and_port);
      }
   }

   if (n_new_sds) {
      printf("  new servers:\n");
      for (i = 0; i < n_new_sds; i++) {
         printf("      %s %s\n",
                mongoc_server_description_type(new_sds[i]),
                mongoc_server_description_host(new_sds[i])->host_and_port);
      }
   }

   prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);

   if (mongoc_topology_description_has_readable_server(new_td, prefs)) {
      printf("  secondary AVAILABLE\n");
   } else {
      printf("  secondary UNAVAILABLE\n");
   }

   if (mongoc_topology_description_has_writable_server(new_td)) {
      printf("  primary AVAILABLE\n");
   } else {
      printf("  primary UNAVAILABLE\n");
   }

   mongoc_read_prefs_destroy(prefs);
   mongoc_server_descriptions_destroy_all(prev_sds, n_prev_sds);
   mongoc_server_descriptions_destroy_all(new_sds, n_new_sds);
}

the way this one prints the old topology β†’ the new topology AND dumps both server lists… obsessed ✨ and notice it checks for a readable secondary with MONGOC_READ_SECONDARY prefs and a writable server separately, then cleans up prefs and both server-description arrays. no leaks, we stan a hygienic icon 🧼

static void
topology_opening(const mongoc_apm_topology_opening_t *event)
{
   stats_t *context;

   context = (stats_t *)mongoc_apm_topology_opening_get_context(event);
   context->topology_opening_events++;

   printf("topology opening\n");
}

static void
topology_closed(const mongoc_apm_topology_closed_t *event)
{
   stats_t *context;

   context = (stats_t *)mongoc_apm_topology_closed_get_context(event);
   context->topology_closed_events++;

   printf("topology closed\n");
}

tiny and adorable, just bump the counter and say hi πŸŽ€

static void
server_heartbeat_started(const mongoc_apm_server_heartbeat_started_t *event)
{
   stats_t *context;

   context = (stats_t *)mongoc_apm_server_heartbeat_started_get_context(event);
   context->heartbeat_started_events++;

   printf("%s heartbeat started\n", mongoc_apm_server_heartbeat_started_get_host(event)->host_and_port);
}

static void
server_heartbeat_succeeded(const mongoc_apm_server_heartbeat_succeeded_t *event)
{
   stats_t *context;
   char *reply;

   context = (stats_t *)mongoc_apm_server_heartbeat_succeeded_get_context(event);
   context->heartbeat_succeeded_events++;

   reply = bson_as_canonical_extended_json(mongoc_apm_server_heartbeat_succeeded_get_reply(event), NULL);

   printf("%s heartbeat succeeded: %s\n", mongoc_apm_server_heartbeat_succeeded_get_host(event)->host_and_port, reply);

   bson_free(reply);
}

static void
server_heartbeat_failed(const mongoc_apm_server_heartbeat_failed_t *event)
{
   stats_t *context;
   bson_error_t error;

   context = (stats_t *)mongoc_apm_server_heartbeat_failed_get_context(event);
   context->heartbeat_failed_events++;
   mongoc_apm_server_heartbeat_failed_get_error(event, &error);

   printf(
      "%s heartbeat failed: %s\n", mongoc_apm_server_heartbeat_failed_get_host(event)->host_and_port, error.message);
}

the succeeded one literally stringifies the reply with bson_as_canonical_extended_json and then bson_frees it β€” memory etiquette, periodt πŸ’… and the failed one pulls the bson_error_t out and prints error.message. iconic. (also: server_heartbeat_failed is πŸ’€ but in a good way)

and now the big one, main β€” the whole vibe check:

int
main(int argc, char *argv[])
{
   mongoc_client_t *client;
   mongoc_apm_callbacks_t *cbs;
   stats_t stats = {0};
   const char *uri_string = "mongodb://127.0.0.1/?appname=sdam-monitoring-example";
   mongoc_uri_t *uri;
   bson_t cmd = BSON_INITIALIZER;
   bson_t reply;
   bson_error_t error;

   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:\n"
              "error message: %s\n",
              error.message);
      return EXIT_FAILURE;
   }

   client = mongoc_client_new_from_uri(uri);
   if (!client) {
      return EXIT_FAILURE;
   }

   mongoc_client_set_error_api(client, 2);
   cbs = mongoc_apm_callbacks_new();
   mongoc_apm_set_server_changed_cb(cbs, server_changed);
   mongoc_apm_set_server_opening_cb(cbs, server_opening);
   mongoc_apm_set_server_closed_cb(cbs, server_closed);
   mongoc_apm_set_topology_changed_cb(cbs, topology_changed);
   mongoc_apm_set_topology_opening_cb(cbs, topology_opening);
   mongoc_apm_set_topology_closed_cb(cbs, topology_closed);
   mongoc_apm_set_server_heartbeat_started_cb(cbs, server_heartbeat_started);
   mongoc_apm_set_server_heartbeat_succeeded_cb(cbs, server_heartbeat_succeeded);
   mongoc_apm_set_server_heartbeat_failed_cb(cbs, server_heartbeat_failed);
   mongoc_client_set_apm_callbacks(client, cbs, (void *)&stats /* context pointer */);

   /* the driver connects on demand to perform first operation */
   BSON_APPEND_INT32(&cmd, "buildinfo", 1);
   mongoc_client_command_simple(client, "admin", &cmd, NULL, &reply, &error);
   mongoc_uri_destroy(uri);
   mongoc_client_destroy(client);

   printf("Events:\n"
          "   server changed: %d\n"
          "   server opening: %d\n"
          "   server closed: %d\n"
          "   topology changed: %d\n"
          "   topology opening: %d\n"
          "   topology closed: %d\n"
          "   heartbeat started: %d\n"
          "   heartbeat succeeded: %d\n"
          "   heartbeat failed: %d\n",
          stats.server_changed_events,
          stats.server_opening_events,
          stats.server_closed_events,
          stats.topology_changed_events,
          stats.topology_opening_events,
          stats.topology_closed_events,
          stats.heartbeat_started_events,
          stats.heartbeat_succeeded_events,
          stats.heartbeat_failed_events);

   bson_destroy(&cmd);
   bson_destroy(&reply);
   mongoc_apm_callbacks_destroy(cbs);

   mongoc_cleanup();

   return EXIT_SUCCESS;
}

so many little details here bestie, don't skip 'em:

  • default uri_string is "mongodb://127.0.0.1/?appname=sdam-monitoring-example" and you can override it with argv[1] if argc > 1
  • URI parse fail β†’ fprintf to stderr with the "failed to parse URI:\n" / "error message: %s\n" lines and return EXIT_FAILURE
  • mongoc_client_new_from_uri fail β†’ plain return EXIT_FAILURE
  • mongoc_client_set_error_api(client, 2) β€” yes, error API version 2
  • all nine mongoc_apm_set_*_cb callbacks get registered, and the context pointer passed to mongoc_client_set_apm_callbacks is (void *)&stats
  • then the /* the driver connects on demand to perform first operation */ comment, BSON_APPEND_INT32(&cmd, "buildinfo", 1) and mongoc_client_command_simple(client, "admin", &cmd, NULL, &reply, &error)
  • cleanup is mongoc_uri_destroy, mongoc_client_destroy, bson_destroy(&cmd), bson_destroy(&reply), mongoc_apm_callbacks_destroy(cbs), mongoc_cleanup(), and it exits EXIT_SUCCESS 🫢

⭐ THE LIL RUNBOOK SECTION ⭐

Start a 3-node replica set on localhost with set name "rs" and start the program:

./example-sdam-monitoring "mongodb://localhost:27017,localhost:27018/?replicaSet=rs"

This example program prints something like:

topology opening
topology changed: Unknown -> ReplicaSetNoPrimary
  secondary UNAVAILABLE
  primary UNAVAILABLE
server opening: localhost:27017
server opening: localhost:27018
localhost:27017 heartbeat started
localhost:27018 heartbeat started
localhost:27017 heartbeat succeeded: { ... reply ... }
server changed: localhost:27017 Unknown -> RSPrimary
server opening: localhost:27019
topology changed: ReplicaSetNoPrimary -> ReplicaSetWithPrimary
  new servers:
      RSPrimary localhost:27017
  secondary UNAVAILABLE
  primary AVAILABLE
localhost:27019 heartbeat started
localhost:27018 heartbeat succeeded: { ... reply ... }
server changed: localhost:27018 Unknown -> RSSecondary
topology changed: ReplicaSetWithPrimary -> ReplicaSetWithPrimary
  previous servers:
      RSPrimary localhost:27017
  new servers:
      RSPrimary localhost:27017
      RSSecondary localhost:27018
  secondary AVAILABLE
  primary AVAILABLE
localhost:27019 heartbeat succeeded: { ... reply ... }
server changed: localhost:27019 Unknown -> RSSecondary
topology changed: ReplicaSetWithPrimary -> ReplicaSetWithPrimary
  previous servers:
      RSPrimary localhost:27017
      RSSecondary localhost:27018
  new servers:
      RSPrimary localhost:27017
      RSSecondary localhost:27018
      RSSecondary localhost:27019
  secondary AVAILABLE
  primary AVAILABLE
topology closed

Events:
   server changed: 3
   server opening: 3
   server closed: 0
   topology changed: 4
   topology opening: 1
   topology closed: 1
   heartbeat started: 3
   heartbeat succeeded: 3
   heartbeat failed: 0

The driver connects to the mongods on ports 27017 and 27018, which were specified in the URI, and determines which is primary. It also discovers the third member, "localhost:27019", and adds it to the topology.

like… it just found the third one?? on its own?? the topology discovery ate and left no crumbs πŸ”₯


πŸ‘‘ AUTHOR

MongoDB, Inc

2009-present, MongoDB, Inc.


and that's the whole thing, bestie β€” you made it to the end of the page πŸŽ€πŸ’– this was MONGOC_REFERENCE(3), version 2.5.6, dated Oct 09, 2026. go forth and monitor some topologies, you gorgeous little sysadmin πŸ¦‹βœ¨
πŸ“¦ where this page comes from