MONGOC_API(3)

NAME
mongoc_api - 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.

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.

  Deprecated feature: automatic initialization and cleanup

On some platforms the driver can automatically call mongoc_init before main, and call mongoc_cleanup as the process exits. This is problematic in situations where related libraries also execute cleanup code on shutdown, and it creates inconsistent rules across platforms. Therefore the automatic initialization and cleanup feature is deprecated, and will be dropped in version 2.0. Meanwhile, for backward compatibility, the feature is enabled by default on platforms where it is available.

For portable, future-proof code, always call mongoc_init and mongoc_cleanup yourself, and configure the driver like:

./configure --disable-automatic-init-and-cleanup

Or with CMake:

cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=NO

LOGGING

MongoDB C driver Logging Abstraction

  Synopsis

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,
            ...) BSON_GNUC_PRINTF (3, 4);
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);

The MongoDB C driver comes with an abstraction for logging that you can use in your application, or integrate with an existing logging system.

  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.

    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_init ();
       mongoc_log_set_handler (my_logger, NULL);
       /* ... your code ...  */
       mongoc_cleanup ();
       return 0;
    }

    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 --enable-tracing to enable function tracing and hex dumps of network packets to STDERR and STDOUT during development and debugging.

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 --enable-tracing will affect its performance. Disabling tracing with mongoc_log_trace_disable() significantly reduces the overhead, but cannot remove it completely. « index

ERROR REPORTING

  Description

Many C Driver functions report errors by returning false or -1 and filling out a bson_error_t structure with an error domain, error code, and message. Use domain to determine which subsystem generated the error, and code for the specific error. message is a human-readable error description.

See also: Handling Errors in libbson.
Domain | Code | Description
MONGOC_ERROR_CLIENT | MONGOC_ERROR_CLIENT_TOO_BIG | You tried to send a message larger than the server's max message size.
 | MONGOC_ERROR_CLIENT_AUTHENTICATE | Wrong credentials, or failure sending or receiving authentication messages.
 | MONGOC_ERROR_CLIENT_NO_ACCEPTABLE_PEER | You tried an SSL connection but the driver was not built with SSL.
 | MONGOC_ERROR_CLIENT_IN_EXHAUST | You began iterating an exhaust cursor, then tried to begin another operation with the same mongoc_client_t.
MONGOC_ERROR_STREAM | MONGOC_ERROR_STREAM_NAME_RESOLUTION | DNS failure.
 | MONGOC_ERROR_STREAM_SOCKET | Timeout communicating with server, or connection closed.
 | MONGOC_ERROR_STREAM_CONNECT | Failed to connect to server.
MONGOC_ERROR_PROTOCOL | MONGOC_ERROR_PROTOCOL_INVALID_REPLY | Corrupt response from server.
 | MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION | The server version is too old or too new to communicate with the driver.
MONGOC_ERROR_CURSOR | MONGOC_ERROR_CURSOR_INVALID_CURSOR | 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.
MONGOC_ERROR_QUERY | MONGOC_ERROR_QUERY_FAILURE | Error API Version 1: Server error from command or query. The server error message is in message.
MONGOC_ERROR_SERVER | MONGOC_ERROR_QUERY_FAILURE | Error API Version 2: Server error from command or query. The server error message is in message.
MONGOC_ERROR_SASL | A SASL error code. | man sasl_errors for a list of codes.
MONGOC_ERROR_BSON | MONGOC_ERROR_BSON_INVALID | You passed an invalid or oversized BSON document as a parameter, or called mongoc_collection_create_index with invalid keys, or the server reply was corrupt.
MONGOC_ERROR_NAMESPACE | MONGOC_ERROR_NAMESPACE_INVALID | You tried to create a collection with an invalid name.
MONGOC_ERROR_COMMAND | MONGOC_ERROR_COMMAND_INVALID_ARG | Many functions set this error code when passed bad parameters. Print the error message for details.
 | MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION | You tried to use a command option the server does not support.
 | MONGOC_ERROR_DUPLICATE_KEY | An insert or update failed because because of a duplicate _id or other unique-index violation.
MONGOC_ERROR_COMMAND | Error code from server. | Error API Version 1: Server error from a command. The server error message is in message.
MONGOC_ERROR_SERVER | Error code from server. | Error API Version 2: Server error from a command. The server error message is in message.
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, mongoc_collection_insert_bulk, mongoc_collection_update, or mongoc_collection_remove.
MONGOC_ERROR_COLLECTION | Error code from server. | Error API Version 1: Server error from mongoc_collection_insert, mongoc_collection_insert_bulk, mongoc_collection_update, or mongoc_collection_remove.
MONGOC_ERROR_SERVER | Error code from server. | Error API Version 2: Server error from mongoc_collection_insert, mongoc_collection_insert_bulk, mongoc_collection_update, or mongoc_collection_remove.
MONGOC_ERROR_GRIDFS | MONGOC_ERROR_GRIDFS_CHUNK_MISSING | The GridFS file is missing a document in its chunks collection.
 | MONGOC_ERROR_GRIDFS_INVALID_FILENAME | You passed a NULL filename to mongoc_gridfs_remove_by_filename.
 | MONGOC_ERROR_GRIDFS_PROTOCOL_ERROR | You called mongoc_gridfs_file_set_id after mongoc_gridfs_file_save.
MONGOC_ERROR_SCRAM | MONGOC_ERROR_SCRAM_PROTOCOL_ERROR | Failure in SCRAM-SHA-1 authentication.
MONGOC_ERROR_SERVER_SELECTION | MONGOC_ERROR_SERVER_SELECTION_FAILURE | No replica set member or mongos is available, or none matches your read preference, or you supplied an invalid mongoc_read_prefs_t.
MONGOC_ERROR_WRITE_CONCERN | Error code from server. | There was a write concern error or timeout from the server.

  Setting the Error API Version

The driver's error reporting began 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 the driver. An application cannot always know where an error originated, and therefore cannot tell what the code means.

For example, if mongoc_collection_update sets the error's domain to MONGOC_ERROR_COLLECTION and its code to 24, the application cannot know whether 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. When the driver uses Version 2 the application can always determine the origin and meaning of error codes. New applications should use Version 2, and existing applications should be updated to use Version 2 as well.
Error Source | API Version 1 | API Version 2
mongoc_cursor_error | MONGOC_ERROR_QUERY | MONGOC_ERROR_SERVER
mongoc_client_command, mongoc_database_command, and other command functions | MONGOC_ERROR_QUERY | MONGOC_ERROR_SERVER
mongoc_collection_count_with_opts, mongoc_client_get_database_names, and other command helper functions | MONGOC_ERROR_QUERY | MONGOC_ERROR_SERVER
mongoc_collection_insert mongoc_collection_insert_bulk mongoc_collection_update mongoc_collection_remove | MONGOC_ERROR_COMMAND | MONGOC_ERROR_SERVER
mongoc_bulk_operation_execute | MONGOC_ERROR_COMMAND | MONGOC_ERROR_SERVER
Write-concern timeout | MONGOC_ERROR_WRITE_CONCERN | MONGOC_ERROR_WRITE_CONCERN

The Error API Versions are defined with MONGOC_ERROR_API_VERSION_LEGACY and MONGOC_ERROR_API_VERSION_2. Set the version with mongoc_client_set_error_api or mongoc_client_pool_set_error_api.

  See Also

MongoDB Server Error Codes

VERSION CHECKS

Conditional compilation based on mongoc version

  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.h>
#define MONGOC_MAJOR_VERSION (1)
#define MONGOC_MINOR_VERSION (6)
#define MONGOC_MICRO_VERSION (3)
#define MONGOC_VERSION_S     "1.6.3"
#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.

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

MONGOC_BULK_OPERATION_T

Bulk Write Operations

  Synopsis

typedef struct _mongoc_bulk_operation_t mongoc_bulk_operation_t;

The opaque type mongoc_bulk_operation_t provides an abstraction for submitting multiple write operations as a single batch.

After adding all of the write operations to the mongoc_bulk_operation_t, call mongoc_bulk_operation_execute() to execute the operation.

WARNING: It is only valid to call mongoc_bulk_operation_execute() once. The mongoc_bulk_operation_t must be destroyed afterwards.

  See Also

Bulk Write Operations

MONGOC_CLIENT_POOL_T

Connection pooling abstraction

  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, this structure is used to retrieve a new mongoc_client_t for a given thread. This structure is thread-safe.

  Example
example-pool.c.INDENT 0.0

/* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs
 * libmongoc-1.0) */
/* ./example-pool [CONNECTION_STRING] */
#include <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 *uristr = "mongodb://127.0.0.1/?appname=pool-example";
   mongoc_uri_t *uri;
   mongoc_client_pool_t *pool;
   pthread_t threads[10];
   unsigned i;
   void *ret;
   pthread_mutex_init (&mutex, NULL);
   mongoc_init ();
   if (argc > 1) {
      uristr = argv[1];
   }
   uri = mongoc_uri_new (uristr);
   if (!uri) {
      fprintf (stderr, "Failed to parse URI: \"%s\".\n", uristr);
      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 0;
}

MONGOC_CLIENT_T

MongoDB Connection Abstraction

  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 provides access to a MongoDB node, replica-set, or sharded-cluster. It maintains management of underlying sockets and routing to individual nodes based on mongoc_read_prefs_t or mongoc_write_concern_t.

  Streams

The underlying transport for a given client can be customized, wrapped or replaced by any implementation that fulfills mongoc_stream_t. A custom transport can be set with mongoc_client_set_stream_initiator().

  Thread Safety

mongoc_client_t is NOT thread-safe and should only be used from one thread at a time. When used in multi-threaded scenarios, it is recommended that you use the thread-safe mongoc_client_pool_t to retrieve a mongoc_client_t for your thread.

  Lifecycle

It is an error to call mongoc_client_destroy on a client that has operations pending. It is required that you release mongoc_collection_t and mongoc_database_t structures before calling mongoc_client_destroy.

  Example
example-client.c.INDENT 0.0

/* gcc example-client.c -o example-client $(pkg-config --cflags --libs
 * libmongoc-1.0) */
/* ./example-client [CONNECTION_STRING [COLLECTION_NAME]] */
#include <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 *uristr = "mongodb://127.0.0.1/?appname=client-example";
   const char *collection_name = "test";
   bson_t query;
   char *str;
   mongoc_init ();
   if (argc > 1) {
      uristr = argv[1];
   }
   if (argc > 2) {
      collection_name = argv[2];
   }
   client = mongoc_client_new (uristr);
   if (!client) {
      fprintf (stderr, "Failed to parse URI.\n");
      return EXIT_FAILURE;
   }
   mongoc_client_set_error_api (client, 2);
   bson_init (&query);
#if 0
   bson_append_utf8 (&query, "hello", -1, "world", -1);
#endif
   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_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_client_destroy (client);
   mongoc_cleanup ();
   return EXIT_SUCCESS;
}

MONGOC_COLLECTION_T

  Synopsis

#include <mongoc.h>
typedef struct _mongoc_collection_t mongoc_collection_t;

mongoc_collection_t provides access to a MongoDB collection. This handle is useful for actions for most CRUD operations, I.e. insert, update, delete, find, etc.

  Read Preferences and Write Concerns

Read preferences and write concerns are inherited from the parent client. They can be overridden by set_* commands if so desired.

  Lifecycle

It is an error to call mongoc_collection_destroy() on a collection that has operations pending. It is required that you release mongoc_cursor_t structures before calling mongoc_collection_destroy().

MONGOC_CURSOR_T

Client-side cursor abtraction

  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.

Cursors are lazy, meaning that no network traffic occurs until the first call to mongoc_cursor_next().

At that point we can:

•   Determine which host we've connected to with mongoc_cursor_get_host().

•   Retrieve more records with repeated calls to mongoc_cursor_next().

•   Clone a query to repeat execution at a later point with mongoc_cursor_clone().

•   Test for errors with mongoc_cursor_error().

  Thread Safety

mongoc_cursor_t is NOT thread safe. It may only be used from the thread it was created from.

  Example
Query MongoDB and iterate results.INDENT 0.0

/* gcc example-client.c -o example-client $(pkg-config --cflags --libs
 * libmongoc-1.0) */
/* ./example-client [CONNECTION_STRING [COLLECTION_NAME]] */
#include <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 *uristr = "mongodb://127.0.0.1/?appname=client-example";
   const char *collection_name = "test";
   bson_t query;
   char *str;
   mongoc_init ();
   if (argc > 1) {
      uristr = argv[1];
   }
   if (argc > 2) {
      collection_name = argv[2];
   }
   client = mongoc_client_new (uristr);
   if (!client) {
      fprintf (stderr, "Failed to parse URI.\n");
      return EXIT_FAILURE;
   }
   mongoc_client_set_error_api (client, 2);
   bson_init (&query);
#if 0
   bson_append_utf8 (&query, "hello", -1, "world", -1);
#endif
   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_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_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 provides access to a MongoDB database. This handle is useful for actions a particular database object. It is not a container for mongoc_collection_t structures.

Read preferences and write concerns are inherited from the parent client. They can be overridden with mongoc_database_set_read_prefs() and mongoc_database_set_write_concern().

WARNING: It is an error to call mongoc_database_destroy() on a database that has operations pending. It is required that you release mongoc_cursor_t structures before calling mongoc_database_destroy.

  Examples

#include <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_DELETE_FLAGS_T

Flags for deletion operations

  Synopsis

typedef enum {
   MONGOC_DELETE_NONE = 0,
   MONGOC_DELETE_SINGLE_REMOVE = 1 << 0,
} mongoc_delete_flags_t;

  Deprecated

WARNING: These flags are deprecated and should not be used in new code.

Please use mongoc_remove_flags_t with mongoc_collection_remove() instead.

MONGOC_FIND_AND_MODIFY_OPTS_T

find_and_modify abstraction

  Synopsis

mongoc_find_and_modify_opts_t is a builder interface to construct a find_and_modify command.

It was created to be able to accommodate new arguments to the MongoDB find_and_modify command.

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

  Example
flags.c.INDENT 0.0

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_json (&reply, NULL);
      printf ("%s\n", str);
      bson_free (str);
   } else {
      fprintf (
         stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
   }
   bson_destroy (&reply);
   bson_destroy (update);
   bson_destroy (&query);
   mongoc_find_and_modify_opts_destroy (opts);
}
bypass.c.INDENT 0.0

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_json (&reply, NULL);
      printf ("%s\n", str);
      bson_free (str);
   } else {
      fprintf (
         stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
   }
   bson_destroy (&reply);
   bson_destroy (update);
   bson_destroy (&query);
   mongoc_find_and_modify_opts_destroy (opts);
}
update.c.INDENT 0.0

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_json (&reply, NULL);
      printf ("%s\n", str);
      bson_free (str);
   } else {
      fprintf (
         stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
   }
   bson_destroy (&reply);
   bson_destroy (update);
   bson_destroy (&query);
   mongoc_find_and_modify_opts_destroy (opts);
}
fields.c.INDENT 0.0

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_json (&reply, NULL);
      printf ("%s\n", str);
      bson_free (str);
   } else {
      fprintf (
         stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
   }
   bson_destroy (&reply);
   bson_destroy (update);
   bson_destroy (&fields);
   bson_destroy (&query);
   mongoc_find_and_modify_opts_destroy (opts);
}
sort.c.INDENT 0.0

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_json (&reply, NULL);
      printf ("%s\n", str);
      bson_free (str);
   } else {
      fprintf (
         stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
   }
   bson_destroy (&reply);
   bson_destroy (update);
   bson_destroy (&sort);
   bson_destroy (&query);
   mongoc_find_and_modify_opts_destroy (opts);
}
opts.c.INDENT 0.0

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;
   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);
   /* 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_json (&reply, NULL);
      printf ("%s\n", str);
      bson_free (str);
   } else {
      fprintf (
         stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
   }
   bson_destroy (&reply);
   bson_destroy (&extra);
   bson_destroy (update);
   bson_destroy (&query);
   mongoc_find_and_modify_opts_destroy (opts);
}
fam.c.INDENT 0.0

#include <bcon.h>
#include <mongoc.h>
#include "flags.c"
#include "bypass.c"
#include "update.c"
#include "fields.c"
#include "opts.c"
#include "sort.c"
int
main (void)
{
   mongoc_collection_t *collection;
   mongoc_database_t *database;
   mongoc_client_t *client;
   bson_error_t error;
   bson_t *options;
   mongoc_init ();
   client = mongoc_client_new (
      "mongodb://localhost:27017/admin?appname=find-and-modify-opts-example");
   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, __LINE__);
      return 1;
   }
   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_database_destroy (database);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
   mongoc_cleanup ();
   return 0;
}

Outputs:

{
    "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.h>
typedef struct _mongoc_gridfs_file_list_t mongoc_gridfs_file_list_t;

  Description

mongoc_gridfs_file_list_t provides a gridfs file list abstraction. It provides iteration and basic marshalling on top of a regular mongoc_collection_find_with_opts() style query. In interface, it's styled after mongoc_cursor_t.

  Example

mongoc_gridfs_file_list_t *list;
mongoc_gridfs_file_t *file;
list = mongoc_gridfs_find (gridfs, query);
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 structure contains options that can be set on a mongoc_gridfs_file_t. It can be used by various functions when creating a new gridfs file.

MONGOC_GRIDFS_FILE_T

  Synopsis

typedef struct _mongoc_gridfs_file_t mongoc_gridfs_file_t;

  Description

This structure provides a MongoDB GridFS file abstraction. It 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 NOT thread-safe and should only be used from one thread at a time.

  Related

•   mongoc_client_t

•   mongoc_gridfs_t

•   mongoc_gridfs_file_list_t

•   mongoc_gridfs_file_opt_t

MONGOC_GRIDFS_T

  Synopsis

#include <mongoc.h>
typedef struct _mongoc_gridfs_t mongoc_gridfs_t;

  Description

mongoc_gridfs_t provides a MongoDB gridfs implementation. The system as a whole is made up of gridfs objects, which contain gridfs_files and gridfs_file_lists. Essentially, a basic file system API.

There are extensive caveats about the kind of use cases gridfs is practical for. In particular, any writing after initial file creation is likely to both break any concurrent readers and be quite expensive. That said, this implementation does allow for arbitrary writes to existing gridfs object, just use them with caution.

mongoc_gridfs also integrates tightly with the mongoc_stream_t abstraction, which provides some convenient wrapping for file creation and reading/writing. It can be used without, but its worth looking 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.

  Thread Safety

mongoc_gridfs_t is NOT thread-safe and should only be used in the same thread as the owning mongoc_client_t.

  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.

  Example
example-gridfs.c.INDENT 0.0

#include <mongoc.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.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;
   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 1;
   }
   mongoc_init ();
   iov.iov_base = (void *) buf;
   iov.iov_len = sizeof buf;
   /* connect to localhost client */
   client =
      mongoc_client_new ("mongodb://127.0.0.1:27017?appname=gridfs-example");
   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 1;
      }
      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) != r) {
            MONGOC_ERROR ("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 1;
      }
      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 1;
      }
      mongoc_gridfs_file_save (file);
      mongoc_gridfs_file_destroy (file);
   } else {
      fprintf (stderr, "Unknown command");
      return 1;
   }
   mongoc_gridfs_destroy (gridfs);
   mongoc_client_destroy (client);
   mongoc_cleanup ();
   return 0;
}

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

The host and port of a MongoDB server. Can be part of a linked list: for example the return value of mongoc_uri_get_hosts when multiple hosts are provided in the MongoDB URI.

  See Also

mongoc_uri_get_hosts and mongoc_cursor_get_host.

MONGOC_INDEX_OPT_GEO_T

  Synopsis

#include <mongoc.h>
typedef struct {
   uint8_t twod_sphere_version;
   uint8_t twod_bits_precision;
   double twod_location_min;
   double twod_location_max;
   double haystack_bucket_size;
   uint8_t *padding[32];
} mongoc_index_opt_geo_t;

  Description

This structure contains the options that may be used for tuning a GEO index.

  See Also

mongoc_index_opt_t

mongoc_index_opt_wt_t

MONGOC_INDEX_OPT_T

  Synopsis

#include <mongoc.h>
typedef struct {
   bool is_initialized;
   bool background;
   bool unique;
   const char *name;
   bool drop_dups;
   bool sparse;
   int32_t expire_after_seconds;
   int32_t v;
   const bson_t *weights;
   const char *default_language;
   const char *language_override;
   mongoc_index_opt_geo_t *geo_options;
   mongoc_index_opt_storage_t *storage_options;
   const bson_t *partial_filter_expression;
   const bson_t *collation;
   void *padding[4];
} mongoc_index_opt_t;

  Description

This structure contains the options that may be used for tuning a specific index.

See the createIndexes documentations in the MongoDB manual for descriptions of individual options.

NOTE: dropDups is deprecated as of MongoDB version 3.0.0. This option is silently ignored by the server and unique index builds using this option will fail if a duplicate value is detected.

  Example

{
   bson_t keys;
   bson_error_t error;
   mongoc_index_opt_t opt;
   mongoc_index_opt_geo_t geo_opt;
   mongoc_index_opt_init (&opt);
   mongoc_index_opt_geo_init (&geo_opt);
   bson_init (&keys);
   BSON_APPEND_UTF8 (&keys, "location", "2d");
   geo_opt.twod_location_min = -123;
   geo_opt.twod_location_max = +123;
   geo_opt.twod_bits_precision = 30;
   opt.geo_options = &geo_opt;
   collection = mongoc_client_get_collection (client, "test", "geo_test");
   if (mongoc_collection_create_index (collection, &keys, &opt, &error)) {
      /* Successfully created the geo index */
   }
   bson_destroy (&keys);
   mongoc_collection_destroy (&collection);
}

  See Also

mongoc_index_opt_geo_t

mongoc_index_opt_wt_t

MONGOC_INDEX_OPT_WT_T

  Synopsis

#include <mongoc.h>
typedef struct {
   mongoc_index_opt_storage_t base;
   const char *config_str;
   void *padding[8];
} mongoc_index_opt_wt_t;

  Description

This structure contains the options that may be used for tuning a WiredTiger specific index.

  See Also

mongoc_index_opt_t

mongoc_index_opt_geo_t

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. They may modify how an insert happens on the MongoDB server.

  Flag Values
MONGOC_INSERT_NONE | Specify no insert flags.
MONGOC_INSERT_CONTINUE_ON_ERROR | Continue inserting documents from the insertion set even if one insert fails.
MONGOC_INSERT_NO_VALIDATE | Do not validate insertion documents before performing an insert. Validation can be expensive, so this can save some time if you know your documents are already valid.

MONGOC_IOVEC_T

  Synopsis

  Synopsis

#include <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 allows for scatter/gather I/O through the socket subsystem.

WARNING: When writing portable code, beware of the ordering of iov_len and iov_base as they are different on various platforms. Therefore, you should not use C initializers for initialization.

MONGOC_MATCHER_T

Client-side document matching abstraction

  Synopsis

typedef struct _mongoc_matcher_t mongoc_matcher_t;

mongoc_matcher_t provides a reduced-interface for client-side matching of BSON documents.

It can perform the basics such as $in, $nin, $eq, $neq, $gt, $gte, $lt, and $lte.

WARNING: mongoc_matcher_t does not currently support the full spectrum of query operations that the MongoDB server supports.

  Deprecated

WARNING: mongoc_matcher_t is deprecated and will be removed in version 2.0.

  Example
Filter a sequence of BSON documents from STDIN based on a query.INDENT 0.0

#include <bcon.h>
#include <bson.h>
#include <mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
   mongoc_matcher_t *matcher;
   bson_reader_t *reader;
   const bson_t *bson;
   bson_t *spec;
   char *str;
   int fd;
   mongoc_init ();
#ifdef _WIN32
   fd = fileno (stdin);
#else
   fd = STDIN_FILENO;
#endif
   reader = bson_reader_new_from_fd (fd, false);
   spec = BCON_NEW ("hello", "world");
   matcher = mongoc_matcher_new (spec, NULL);
   while ((bson = bson_reader_read (reader, NULL))) {
      if (mongoc_matcher_match (matcher, bson)) {
         str = bson_as_json (bson, NULL);
         printf ("%s\n", str);
         bson_free (str);
      }
   }
   bson_reader_destroy (reader);
   bson_destroy (spec);
   mongoc_cleanup ();
   return 0;
}

MONGOC_QUERY_FLAGS_T

Flags for query operations

  Synopsis

typedef enum {
   MONGOC_QUERY_NONE = 0,
   MONGOC_QUERY_TAILABLE_CURSOR = 1 << 1,
   MONGOC_QUERY_SLAVE_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. They may be bitwise or'd together. They may modify how a query is performed in the MongoDB server.

  Flag Values
MONGOC_QUERY_NONE | Specify no query flags.
MONGOC_QUERY_TAILABLE_CURSOR | Cursor will not be closed when the last data is retrieved. You can resume this cursor later.
MONGOC_QUERY_SLAVE_OK | Allow query of replica set secondaries.
MONGOC_QUERY_OPLOG_REPLAY | Used internally by MongoDB.
MONGOC_QUERY_NO_CURSOR_TIMEOUT | The server normally times out an idle cursor after an inactivity period (10 minutes). This prevents that.
MONGOC_QUERY_AWAIT_DATA | Use with MONGOC_QUERY_TAILABLE_CURSOR. Block rather than returning no data. After a period, time out.
MONGOC_QUERY_EXHAUST | Stream the data down full blast in multiple "reply" packets. Faster when you are pulling down a lot of data and you know you want to retrieve it all.
MONGOC_QUERY_PARTIAL | Get partial results from mongos if some shards are down (instead of throwing an error).

MONGOC_RAND

MongoDB Random Number Generator

  Synopsis

void
mongoc_rand_add (const void *buf, int num, doubel entropy);
void
mongoc_rand_seed (const void *buf, int num);
int
mongoc_rand_status (void);

  Description

The mongoc_rand family of functions provide access to the low level randomness primitives used by the MongoDB C Driver. In particular, they control the creation of cryptographically strong pseudo-random bytes required by some security mechanisms.

While we can usually pull enough entropy from the environment, you may be required to seed the PRNG manually depending on your OS, hardware and other entropy consumers running on the same system.

  Entropy

mongoc_rand_add and mongoc_rand_seed allow the user to directly provide entropy. They differ insofar as mongoc_rand_seed requires that each bit provided is fully random. mongoc_rand_add allows the user to specify the degree of randomness in the provided bytes as well.

  Status

The mongoc_rand_status function allows the user to check the status of the mongoc PRNG. This can be used to guarantee sufficient entropy at program startup, rather than waiting for runtime errors to occur.

MONGOC_READ_CONCERN_T

Read Concern abstraction

  Synopsis

New in MongoDB 3.2.

The mongoc_read_concern_t allows clients to choose a level of isolation for their reads. The default, MONGOC_READ_CONCERN_LEVEL_LOCAL, is right for the great majority of applications.

You can specify a read concern on connection objects, database objects, or collection objects.

See readConcern on the MongoDB website for more information.

Read Concern is only sent to MongoDB when it has explicitly been set by mongoc_read_concern_set_level to anything other then empty string.

  Read Concern Levels
MONGOC_READ_CONCERN_LEVEL_LOCAL | Default. Uses read concern level "local".
MONGOC_READ_CONCERN_LEVEL_MAJORITY | Uses read concern level "majority".
MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE | Uses read concern level "linearizable".

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 prefences. It allows for hinting to the driver which nodes in a replica set should be accessed first.

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, MONGOC_READ_PRIMARY. All of the other modes come with caveats that won't be covered in great detail here.

  Read Modes
MONGOC_READ_PRIMARY | Default mode. All operations read from the current replica set primary.
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 is unavailable, operations read from secondary members.
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 allow you to specify custom read preferences and write concerns so that your application can target operations to specific members.

Custom read preferences and write concerns evaluate tags sets in different ways: read preferences consider the value of a tag when selecting a member to read from. while write concerns ignore the value of a tag to 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. However, 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.

    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.

  Max Staleness

When connected to replica set running MongoDB 3.4 or later, the driver estimates the staleness of each secondary based on lastWriteDate values provided in server isMaster 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. Otherwise, it must be a positive integer at least MONGOC_SMALLEST_MAX_STALENESS_SECONDS (90 seconds).

Max Staleness is also supported by sharded clusters of replica sets if all servers run MongoDB 3.4 or later.

MONGOC_REMOVE_FLAGS_T

Flags for deletion operations

  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. They may change the number of documents that are removed during a remove command.

  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_REPLY_FLAGS_T

Flags from server replies

  Synopsis

typedef enum {
   MONGOC_REPLY_NONE = 0,
   MONGOC_REPLY_CURSOR_NOT_FOUND = 1 << 0,
   MONGOC_REPLY_QUERY_FAILURE = 1 << 1,
   MONGOC_REPLY_SHARD_CONFIG_STALE = 1 << 2,
   MONGOC_REPLY_AWAIT_CAPABLE = 1 << 3,
} mongoc_reply_flags_t;

  Description

These flags correspond to the wire protocol. They may be bitwise or'd together.

  Flag Values
MONGOC_REPLY_NONE | No flags set.
MONGOC_REPLY_CURSOR_NOT_FOUND | No matching cursor was found on the server.
MONGOC_REPLY_QUERY_FAILURE | The query failed or was invalid. Error document has been provided.
MONGOC_REPLY_SHARD_CONFIG_STALE | Shard config is stale.
MONGOC_REPLY_AWAIT_CAPABLE | If the returned cursor is capable of MONGOC_QUERY_AWAIT_DATA.

MONGOC_SERVER_DESCRIPTION_T

Server description

  Synopsis

#include <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.

See also mongoc_client_get_server_descriptions().

  Lifecycle

Clean up with mongoc_server_description_destroy().

MONGOC_SOCKET_T

Portable socket abstraction

  Synopsis

#include <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 *padding[7];
} mongoc_ssl_opt_t;

  Description

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

Beginning in version 1.2.0, once a pool or client has any SSL options set, all connections use SSL, even if ssl=true is omitted from the MongoDB URI. Before, SSL options were ignored unless ssl=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.

  Client Authentication

When MongoDB is started with SSL enabled, it will by default require the client o provide a client certificate issued by a certificate authority specified by --sslCAFile, or an authority trusted by the native certificate store in use on the server.

To provide the client certificate, the user must configure the pem_file to point at a PEM armored certificate.

mongoc_ssl_opt_t ssl_opts = {0};
ssl_opts.pem_file = "/path/to/client-certificate.pem"
   /* Then set the client ssl_opts, when using a single client mongoc_client_t
      */
   mongoc_client_pool_set_ssl_opts (pool, &ssl_opts);
/* or, set the pool ssl_opts, when using a the thread safe mongoc_client_pool_t
 */
mongoc_client_set_ssl_opts (client, &ssl_opts);

  Server Certificate Verification

The MongoDB C Driver will automatically verify the validity of the server certificate, such as issued by configured Certificate Authority, hostname validation, and expiration.

To overwrite this behaviour, it is possible to disable hostname validation, and/or allow otherwise invalid certificates. This behaviour is controlled using the allow_invalid_hostname and weak_cert_validation fields. By default, both are set to false. It is not recommended to change these defaults as it exposes the client to Man In The Middle attacks (when allow_invalid_hostname is set) and otherwise invalid certificates when weak_cert_validation is set to true.

  Native TLS Support on Linux (OpenSSL)

The MongoDB C Driver supports the dominating TLS library (OpenSSL) and crypto libraries (OpenSSL's libcrypto) on Linux and Unix platforms.

Support for OpenSSL 1.1 and later was added in 1.4.0.

When compiled against OpenSSL, the driver will attempt to load the system default certificate store, as configured by the distribution, if the ca_file and ca_dir are not set.

  Native TLS Support on Windows (Secure Channel)

The MongoDB C Driver supports the Windows native TLS library (Secure Channel, or SChannel), and its native crypto library (Cryptography API: Next Generation, or CNG).

When compiled against the Windows native libraries, the ca_dir option is not supported, and will issue an error if used.

Encrypted PEM files (e.g., requiring pem_pwd) are also not supported, and will result in error when attempting to load them.

When ca_file is provided, the driver will only allow server certificates issued by the authority (or authorities) provided. When no ca_file is provided, the driver will look up the Certificate Authority using the System Local Machine Root certificate store to confirm the provided certificate.

When crl_file is provided, the driver will import the revocation list to the System Local Machine Root certificate store.

  Native TLS Support on Mac OS X / Darwin (Secure Transport)

The MongoDB C Driver supports the Darwin (OS X, macOS, iOS, etc.) native TLS library (Secure Transport), and its native crypto library (Common Crypto, or CC).

When compiled against Secure Transport, the ca_dir option is not supported, and will issue an error if used.

When ca_file is provided, the driver will only allow server certificates issued by the authority (or authorities) provided. When no ca_file is provided, the driver will use the Certificate Authorities in the currently unlocked keychains.

  See Also

•   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_GRIDFS_T

  Synopsis

typedef struct _mongoc_stream_gridfs_t mongoc_stream_gridfs_t

The mongoc_stream_gridfs_t class is an implementation of mongoc_stream_t for files stored in GridFS. It allows for transparently streaming GridFS files from a MongoDB server.

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 SSL 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_gridfs_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 OpenSSL 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. See Introduction to Application Performance Monitoring.

MONGOC_UPDATE_FLAGS_T

Flags for update operations

  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. The allow for modifying the way an update is performed in the MongoDB server.

  Flag Values
MONGOC_UPDATE_NONE | No update flags set.
MONGOC_UPDATE_UPSERT | If an upsert should be performed.
MONGOC_UPDATE_MULTI_UPDATE | If more than a single matching document should be updated. By default only the first document is updated.
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.

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 provides standardized parsing as well as convenience methods for extracting useful information such as replica hosts or authorization information.

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

  Format

mongodb://                                   <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.

2.  An optional username and password.

3.  The only required part of the uri. This specifies either a hostname, IP address or UNIX domain socket.

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.

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.

  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 the connection string that resembles the following.

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

  Connection Options
ssl | {true|false}, indicating if SSL must be used. (See also mongoc_client_set_ssl_opts and mongoc_client_pool_set_ssl_opts.)
connectTimeoutMS | A timeout in milliseconds to attempt a connection before timing out. This setting applies to server discovery and monitoring connections as well as to connections for application operations. The default is 10 seconds.
socketTimeoutMS | The time in milliseconds to attempt to send or receive on a socket before the attempt times out. The default is 5 minutes.

Setting any of the *TimeoutMS options above to 0 will be interpreted as "use the default value".

  Server Discovery, Monitoring, and Selection Options

Clients in a mongoc_client_pool_t share a topology scanner that runs on a background thread. The thread wakes every heartbeatFrequencyMS (default 10 seconds) to scan all MongoDB servers in parallel. Whenever an application operation requires a server that is not known--for example, if there is no known primary and your application attempts an insert--the thread rescans all servers every half-second. In this situation the pooled client waits up to serverSelectionTimeoutMS (default 30 seconds) for the thread to find a server suitable for the operation, then returns an error with domain MONGOC_ERROR_SERVER_SELECTION.

Technically, the total time an operation may wait while a pooled client scans the topology is controlled both by serverSelectionTimeoutMS and connectTimeoutMS. The longest wait occurs if the last scan begins just at the end of the selection timeout, and a slow or down server requires the full connection timeout before the client gives up.

A non-pooled client is single-threaded. Every heartbeatFrequencyMS, it blocks the next application operation while it does a parallel scan. This scan takes as long as needed to check the slowest server: roughly connectTimeoutMS. Therefore the default heartbeatFrequencyMS for single-threaded clients is greater than for pooled clients: 60 seconds.

By default, single-threaded (non-pooled) clients scan only once when an operation requires a server that is not known. If you attempt an insert and there is no known primary, the client checks all servers once trying to find it, then 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.

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 serverSelectionTimeoutMS and connectTimeoutMS if serverSelectionTryOnce is set "false".
heartbeatFrequencyMS | The interval between server monitoring checks. Defaults to 10 seconds in pooled (multi-threaded) mode, 60 seconds in non-pooled mode (single-threaded).
serverSelectionTimeoutMS | A timeout in milliseconds to block for server selection before throwing an exception. The default is 30 seconds.
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 is false, then the driver repeatedly searches for a suitable server for up to serverSelectionTimeoutMS milliseconds (pausing a half second between attempts). The default for serverSelectionTryOnce is "false" for pooled clients, otherwise "true". Pooled clients ignore serverSelectionTryOnce; they signal the thread to rescan the topology every half-second until serverSelectionTimeoutMS expires.
socketCheckIntervalMS | Only applies to single threaded clients. If a socket has not been used within this time, its connection is checked with a quick "isMaster" call before it is used again. Defaults to 5 seconds.

Setting any of the *TimeoutMS options above to 0 will be interpreted as "use the default value".

  Connection Pool Options

These options govern the behavior of a mongoc_client_pool_t. They are ignored by a non-pooled mongoc_client_t.
maxPoolSize | The maximum number of clients created by a mongoc_client_pool_t total (both in the pool and checked out). The default value is 100. Once it is reached, mongoc_client_pool_pop blocks until another thread pushes a client.
minPoolSize | The number of clients to keep in the pool; once it is reached, mongoc_client_pool_push destroys clients instead of pushing them. The default value, 0, means "no minimum": a client pushed into the pool is always stored, not destroyed.
maxIdleTimeMS | Not implemented.
waitQueueMultiple | Not implemented.
waitQueueTimeoutMS | Not implemented.

  Write Concern Options
w | 0 | The driver will not acknowledge write operations but will pass or handle any network and socket errors that it receives to the client. If you disable write concern but enable the getLastError command’s w option, w overrides the w option.
 | 1 | Provides basic acknowledgment 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 w option, write operations will only return successfully after a majority of the configured replica set members have acknowledged the write operation.
 | 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. 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, potentially indefinitely, for these members to become available.
 | 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.
wtimeoutMS |  | The time in milliseconds to wait for replication to succeed, as specified in the w option, before timing out. When wtimeoutMS is 0, write operations will never time out.
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 acknowledgment 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.

  Read Concern Options
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.

  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.

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.
    readPreference | Specifies the replica set read preference for this connection. This setting overrides any slaveOk value. The read preference values are the following: primary (default) primaryPreferred secondary secondaryPreferred nearest
    readPreferenceTags | Specifies a tag set as a comma-separated list of colon-separated key-value pairs. Cannot be combined with preference "primary".
    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.

    NOTE: "localThresholdMS" is ignored when talking to replica sets through a mongos. The equivalent is mongos's localThreshold command line option.

MONGOC_WRITE_CONCERN_T

Write Concern abstraction

  Synopsis

mongoc_write_concern_t tells the driver what level of acknowledgment to await from the server. The default, MONGOC_WRITE_CONCERN_W_DEFAULT, is right for the great majority of applications.

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:

•   mongoc_client_command

•   mongoc_client_command_simple

•   mongoc_database_command

•   mongoc_database_command_simple

•   mongoc_collection_command

•   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.

    See Write Concern on the MongoDB website for more information.

  Write Concern Levels

Set the write concern level with mongoc_write_concern_set_w.
MONGOC_WRITE_CONCERN_W_DEFAULT (1) | By default, writes block awaiting acknowledgment from MongoDB. Acknowledged write concern allows clients to catch network, duplicate key, and other errors.
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.
MONGOC_WRITE_CONCERN_W_MAJORITY (majority) | Block until a write has been propagated to a majority of the nodes in the replica set.
n | Block until a write has been propagated to at least n nodes in the replica set.

  Deprecations

The write concern MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED (value -1) is a deprecated synonym for MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED (value 0), and will be removed in the next major release.

mongoc_write_concern_set_fsync is deprecated.

AUTHOR
MongoDB, Inc

COPYRIGHT
2017, MongoDB, Inc