Object Lifecycle — MongoDB C Driver 1.9.2

- MongoDB C Driver 1.9.2 »
- API Reference

# Object Lifecycle

This page documents the order of creation and destruction for libmongoc’s main struct types.

## Clients and pools

Call mongoc_init() once, before calling any other libmongoc functions, and call mongoc_cleanup() once before your program exits.

A program that uses libmongoc from multiple threads should create a mongoc_client_pool_t with mongoc_client_pool_new(). Each thread acquires a mongoc_client_t from the pool with mongoc_client_pool_pop() and returns it with mongoc_client_pool_push() when the thread is finished using it. To destroy the pool, first return all clients, then call mongoc_client_pool_destroy().

If your program uses libmongoc from only one thread, create a mongoc_client_t directly with mongoc_client_new() or mongoc_client_new_from_uri(). Destroy it with mongoc_client_destroy().

## Databases, collections, and related objects

You can create a mongoc_database_t or mongoc_collection_t from a mongoc_client_t, and create a mongoc_cursor_t or mongoc_bulk_operation_t from a mongoc_collection_t.

Each of these objects must be destroyed before the client they were created from, but their lifetimes are otherwise independent.

## GridFS objects

You can create a mongoc_gridfs_t from a mongoc_client_t, create a mongoc_gridfs_file_t or 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.

Each of these objects depends on the object it was created from. Always destroy GridFS objects in the reverse of the order they were created. The sole exception is that a mongoc_gridfs_file_t need not be destroyed before the mongoc_gridfs_file_list_t it was created from.

## Sessions

Start a session with mongoc_client_start_session(), use the session for a sequence of operations, then free it with mongoc_client_session_destroy(). A session must be freed before the mongoc_client_t it came from.

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 not causally consistent. If you execute a write operation with a mongoc_write_concern_t on which you have called mongoc_write_concern_set_w() with a value of 0, the write does not participate in causal consistency.

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.

Created using Sphinx 1.6.5, based on Sphinx Readable Theme.