mongoc_apm_callbacks_destroy.3
MONGOC_APM_CALLBACKS_DESTROY(3) libmongoc MONGOC_APM_CALLBACKS_DESTROY(3)
SYNOPSIS
void
mongoc_apm_callbacks_destroy (mongoc_apm_callbacks_t *callbacks);
Free a mongoc_apm_callbacks_t. Does nothing if callbacks is NULL.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_CALLBACKS_DESTROY(3)
mongoc_apm_callbacks_new.3
MONGOC_APM_CALLBACKS_NEW(3) libmongoc MONGOC_APM_CALLBACKS_NEW(3)
SYNOPSIS
mongoc_apm_callbacks_t *
mongoc_apm_callbacks_new (void);
Create a struct to hold event-notification callbacks.
RETURNS
A new mongoc_apm_callbacks_t you must free with
mongoc_apm_callbacks_destroy().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_CALLBACKS_NEW(3)
mongoc_apm_callbacks_t.3
MONGOC_APM_CALLBACKS_T(3) libmongoc MONGOC_APM_CALLBACKS_T(3)
Notification callbacks
SYNOPSIS
Used to receive notification of events, such as when a MongoDB command
begins, succeeds, or fails.
Create a mongoc_apm_callbacks_t with mongoc_apm_callbacks_new(), set
callbacks on it, then pass it to mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_CALLBACKS_T(3)
mongoc_apm_command_failed_get_command_name.3
MONGOC_APM_COMMAND_FAILED_GET_COMMANDbNAME(3)OMMAND_FAILED_GET_COMMAND_NAME(3)
SYNOPSIS
const char *
mongoc_apm_command_failed_get_command_name (
const mongoc_apm_command_failed_t *event);
Returns this event's command name. The data is only valid in the scope
of the callback that receives this event; copy it if it will be ac-
cessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
A string that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,A2025OMMAND_FAILED_GET_COMMAND_NAME(3)
mongoc_apm_command_failed_get_context.3
MONGOC_APM_COMMAND_FAILED_GET_CONTEXT(3)ngoc_APM_COMMAND_FAILED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_command_failed_get_context (
const mongoc_apm_command_failed_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025APM_COMMAND_FAILED_GET_CONTEXT(3)
mongoc_apm_command_failed_get_database_name.3
MONGOC_APM_COMMAND_FAILED_GET_DATABASEmNAME(3)MAND_FAILED_GET_DATABASE_NAME(3)
SYNOPSIS
const char *
mongoc_apm_command_failed_get_database_name (
const mongoc_apm_command_failed_t *event);
Returns this event's database name. The data is only valid in the scope
of the callback that receives this event; copy it if it will be ac-
cessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
A string that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,P2025MMAND_FAILED_GET_DATABASE_NAME(3)
mongoc_apm_command_failed_get_duration.3
MONGOC_APM_COMMAND_FAILED_GET_DURATION(3)gocAPM_COMMAND_FAILED_GET_DURATION(3)
SYNOPSIS
int64_t
mongoc_apm_command_failed_get_duration (
const mongoc_apm_command_failed_t *event);
Returns this event's duration in microseconds.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
The event's duration.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025PM_COMMAND_FAILED_GET_DURATION(3)
mongoc_apm_command_failed_get_error.3
MONGOC_APM_COMMAND_FAILED_GET_ERROR(3)mongocOC_APM_COMMAND_FAILED_GET_ERROR(3)
SYNOPSIS
void
mongoc_apm_command_failed_get_error (const mongoc_apm_command_failed_t *event,
bson_error_t *error);
Copies this event's error info.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
+ error: A bson_error_t to receive the event's error info.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_APM_COMMAND_FAILED_GET_ERROR(3)
mongoc_apm_command_failed_get_host.3
MONGOC_APM_COMMAND_FAILED_GET_HOST(3)bmongocGOC_APM_COMMAND_FAILED_GET_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_apm_command_failed_get_host (const mongoc_apm_command_failed_t *event);
Returns this event's host. This mongoc_host_list_t is not part of a
linked list, it is solely the server for this event. The data is only
valid in the scope of the callback that receives this event; copy it if
it will be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
A mongoc_host_list_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_APM_COMMAND_FAILED_GET_HOST(3)
mongoc_apm_command_failed_get_operation_id.3
MONGOC_APM_COMMAND_FAILED_GET_OPERATIONoID(3)OMMAND_FAILED_GET_OPERATION_ID(3)
SYNOPSIS
int64_t
mongoc_apm_command_failed_get_operation_id (
const mongoc_apm_command_failed_t *event);
Returns this event's operation id. This number correlates all the com-
mands in a bulk operation, or all the "find" and "getMore" commands re-
quired to stream a large query result.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
The event's operation id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,A2025OMMAND_FAILED_GET_OPERATION_ID(3)
mongoc_apm_command_failed_get_reply.3
MONGOC_APM_COMMAND_FAILED_GET_REPLY(3)mongocOC_APM_COMMAND_FAILED_GET_REPLY(3)
SYNOPSIS
const bson_t *
mongoc_apm_command_failed_get_reply (
const mongoc_apm_command_failed_t *event);
Returns the server's reply to a command that failed. The reply contains
details about why the command failed. If no server reply was received,
such as in the event of a network error, then the reply is a valid
empty BSON document. The data is only valid in the scope of the call-
back that receives this event; copy it if it will be accessed after the
callback returns.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
A bson_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_APM_COMMAND_FAILED_GET_REPLY(3)
mongoc_apm_command_failed_get_request_id.3
MONGOC_APM_COMMAND_FAILED_GET_REQUESTbID(3)cM_COMMAND_FAILED_GET_REQUEST_ID(3)
SYNOPSIS
int64_t
mongoc_apm_command_failed_get_request_id (
const mongoc_apm_command_failed_t *event);
Returns this event's wire-protocol request id. Use this number to cor-
relate client-side events with server log messages.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
The event's request id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025_COMMAND_FAILED_GET_REQUEST_ID(3)
mongoc_apm_command_failed_get_server_connection_id_int64.3
MONGOC_APM_COMMAND_FAILED_GET_SERVERiCONNECTIONTIDEINT64(3)NECTION_ID_INT64(3)
SYNOPSIS
int64_t
mongoc_apm_command_failed_get_server_connection_id_int64 (
const mongoc_apm_command_failed_t *event);
Returns this event's context.
Returns the server connection ID for the command. The server connection
ID is distinct from the server ID (-
mongoc_apm_command_failed_get_server_id()) and is returned by the hello
or legacy hello response as "connectionId" from the server on 4.2+.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
The server connection ID as a positive integer or -1 if it is not
available.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_APM_COMMayD12,I2025GET_SERVER_CONNECTION_ID_INT64(3)
mongoc_apm_command_failed_get_server_id.3
MONGOC_APM_COMMAND_FAILED_GET_SERVERiID(3)ocPM_COMMAND_FAILED_GET_SERVER_ID(3)
SYNOPSIS
uint32_t
mongoc_apm_command_failed_get_server_id (
const mongoc_apm_command_failed_t *event);
Returns this event's server id.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
The event's server id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025M_COMMAND_FAILED_GET_SERVER_ID(3)
mongoc_apm_command_failed_get_service_id.3
MONGOC_APM_COMMAND_FAILED_GET_SERVICEbID(3)cM_COMMAND_FAILED_GET_SERVICE_ID(3)
SYNOPSIS
const bson_oid_t *
mongoc_apm_command_failed_get_service_id (
const mongoc_apm_command_failed_t *event);
Returns this event's service ID, which identifies the MongoDB service
behind a load balancer, or NULL if not connected to a load balanced
cluster.
PARAMETERS
+ event: A mongoc_apm_command_failed_t.
RETURNS
A bson_oid_t that should not be modified or freed or NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025_COMMAND_FAILED_GET_SERVICE_ID(3)
mongoc_apm_command_failed_t.3
MONGOC_APM_COMMAND_FAILED_T(3) libmongoc MONGOC_APM_COMMAND_FAILED_T(3)
Command-failed event
SYNOPSIS
An event notification sent when the driver fails to execute a MongoDB
command.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_COMMAND_FAILED_T(3)
mongoc_apm_command_started_get_command.3
MONGOC_APM_COMMAND_STARTED_GET_COMMAND(3)gocAPM_COMMAND_STARTED_GET_COMMAND(3)
SYNOPSIS
const bson_t *
mongoc_apm_command_started_get_command (
const mongoc_apm_command_started_t *event);
Returns this event's command. The data is only valid in the scope of
the callback that receives this event; copy it if it will be accessed
after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
A bson_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025PM_COMMAND_STARTED_GET_COMMAND(3)
mongoc_apm_command_started_get_command_name.3
MONGOC_APM_COMMAND_STARTED_GET_COMMANDmNAME(3)MAND_STARTED_GET_COMMAND_NAME(3)
SYNOPSIS
const char *
mongoc_apm_command_started_get_command_name (
const mongoc_apm_command_started_t *event);
Returns this event's command name. The data is only valid in the scope
of the callback that receives this event; copy it if it will be ac-
cessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
A string that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,P2025MMAND_STARTED_GET_COMMAND_NAME(3)
mongoc_apm_command_started_get_context.3
MONGOC_APM_COMMAND_STARTED_GET_CONTEXT(3)gocAPM_COMMAND_STARTED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_command_started_get_context (
const mongoc_apm_command_started_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025PM_COMMAND_STARTED_GET_CONTEXT(3)
mongoc_apm_command_started_get_database_name.3
MONGOC_APM_COMMAND_STARTED_GET_DATABASEoNAME(3)ND_STARTED_GET_DATABASE_NAME(3)
SYNOPSIS
const char *
mongoc_apm_command_started_get_database_name (
const mongoc_apm_command_started_t *event);
Returns this event's database name. The data is only valid in the scope
of the callback that receives this event; copy it if it will be ac-
cessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
A string that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,M2025MAND_STARTED_GET_DATABASE_NAME(3)
mongoc_apm_command_started_get_host.3
MONGOC_APM_COMMAND_STARTED_GET_HOST(3)mongocOC_APM_COMMAND_STARTED_GET_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_apm_command_started_get_host (const mongoc_apm_command_started_t *event);
Returns this event's host. This mongoc_host_list_t is not part of a
linked list, it is solely the server for this event. The data is only
valid in the scope of the callback that receives this event; copy it if
it will be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
A mongoc_host_list_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_APM_COMMAND_STARTED_GET_HOST(3)
mongoc_apm_command_started_get_operation_id.3
MONGOC_APM_COMMAND_STARTED_GET_OPERATIONnID(3)MAND_STARTED_GET_OPERATION_ID(3)
SYNOPSIS
int64_t
mongoc_apm_command_started_get_operation_id (
const mongoc_apm_command_started_t *event);
Returns this event's operation id. This number correlates all the com-
mands in a bulk operation, or all the "find" and "getMore" commands re-
quired to stream a large query result.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
The event's operation id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,P2025MMAND_STARTED_GET_OPERATION_ID(3)
mongoc_apm_command_started_get_request_id.3
MONGOC_APM_COMMAND_STARTED_GET_REQUESTmID(3)_COMMAND_STARTED_GET_REQUEST_ID(3)
SYNOPSIS
int64_t
mongoc_apm_command_started_get_request_id (
const mongoc_apm_command_started_t *event);
Returns this event's wire-protocol request id. Use this number to cor-
relate client-side events with server log messages.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
The event's request id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025COMMAND_STARTED_GET_REQUEST_ID(3)
mongoc_apm_command_started_get_server_connection_id_int64.3
MONGOC_APM_COMMANDMSTARTEDPGETOSERVERbCONNECTION_IDRINT64(3)ECTION_ID_INT64(3)
SYNOPSIS
int64_t
mongoc_apm_command_started_get_server_connection_id_int64 (
const mongoc_apm_command_started_t *event);
Returns the server connection ID for the command. The server connection
ID is distinct from the server ID (-
mongoc_apm_command_started_get_server_id()) and is returned by the
hello or legacy hello response as "connectionId" from the server on
4.2+.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
The server connection ID as a positive integer or -1 if it is not
available.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_APM_COMMMay_12,R2025GET_SERVER_CONNECTION_ID_INT64(3)
mongoc_apm_command_started_get_server_id.3
MONGOC_APM_COMMAND_STARTED_GET_SERVERbID(3)cM_COMMAND_STARTED_GET_SERVER_ID(3)
SYNOPSIS
uint32_t
mongoc_apm_command_started_get_server_id (
const mongoc_apm_command_started_t *event);
Returns this event's server id.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
The event's server id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025_COMMAND_STARTED_GET_SERVER_ID(3)
mongoc_apm_command_started_get_service_id.3
MONGOC_APM_COMMAND_STARTED_GET_SERVICEmID(3)_COMMAND_STARTED_GET_SERVICE_ID(3)
SYNOPSIS
const bson_oid_t *
mongoc_apm_command_started_get_service_id (
const mongoc_apm_command_started_t *event);
Returns this event's service ID, which identifies the MongoDB service
behind a load balancer, or NULL if not connected to a load balanced
cluster.
PARAMETERS
+ event: A mongoc_apm_command_started_t.
RETURNS
A bson_oid_t that should not be modified or freed or NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025COMMAND_STARTED_GET_SERVICE_ID(3)
mongoc_apm_command_started_t.3
MONGOC_APM_COMMAND_STARTED_T(3) libmongoc MONGOC_APM_COMMAND_STARTED_T(3)
Command-started event
SYNOPSIS
An event notification sent when the driver begins executing a MongoDB
command.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_COMMAND_STARTED_T(3)
mongoc_apm_command_succeeded_get_command_name.3
MONGOC_APM_COMMAND_SUCCEEDED_GETNCOMMANDnNAME(3)_SUCCEEDED_GET_COMMAND_NAME(3)
SYNOPSIS
const char *
mongoc_apm_command_succeeded_get_command_name (
const mongoc_apm_command_succeeded_t *event);
Returns this event's command name. The data is only valid in the scope
of the callback that receives this event; copy it if it will be ac-
cessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
A string that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,_2025AND_SUCCEEDED_GET_COMMAND_NAME(3)
mongoc_apm_command_succeeded_get_context.3
MONGOC_APM_COMMAND_SUCCEEDED_GET_CONTEXT(3)cM_COMMAND_SUCCEEDED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_command_succeeded_get_context (
const mongoc_apm_command_succeeded_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025_COMMAND_SUCCEEDED_GET_CONTEXT(3)
mongoc_apm_command_succeeded_get_database_name.3
MONGOC_APM_COMMAND_SUCCEEDED_GETGDATABASEgNAME(3)UCCEEDED_GET_DATABASE_NAME(3)
SYNOPSIS
const char *
mongoc_apm_command_succeeded_get_database_name (
const mongoc_apm_command_succeeded_t *event);
Returns this event's database name. The data is only valid in the scope
of the callback that receives this event; copy it if it will be ac-
cessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
A string that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayA12,C2025ND_SUCCEEDED_GET_DATABASE_NAME(3)
mongoc_apm_command_succeeded_get_duration.3
MONGOC_APM_COMMAND_SUCCEEDED_GET_DURATION(3)_COMMAND_SUCCEEDED_GET_DURATION(3)
SYNOPSIS
int64_t
mongoc_apm_command_succeeded_get_duration (
const mongoc_apm_command_succeeded_t *event);
Returns this event's duration in microseconds.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
The event's duration.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025COMMAND_SUCCEEDED_GET_DURATION(3)
mongoc_apm_command_succeeded_get_host.3
MONGOC_APM_COMMAND_SUCCEEDED_GET_HOST(3)ngoc_APM_COMMAND_SUCCEEDED_GET_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_apm_command_succeeded_get_host (
const mongoc_apm_command_succeeded_t *event);
Returns this event's host. This mongoc_host_list_t is not part of a
linked list, it is solely the server for this event. The data is only
valid in the scope of the callback that receives this event; copy it if
it will be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
A mongoc_host_list_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025APM_COMMAND_SUCCEEDED_GET_HOST(3)
mongoc_apm_command_succeeded_get_operation_id.3
MONGOC_APM_COMMAND_SUCCEEDED_GETNOPERATIONoID(3)_SUCCEEDED_GET_OPERATION_ID(3)
SYNOPSIS
int64_t
mongoc_apm_command_succeeded_get_operation_id (
const mongoc_apm_command_succeeded_t *event);
Returns this event's operation id. This number correlates all the com-
mands in a bulk operation, or all the "find" and "getMore" commands re-
quired to stream a large query result.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
The event's operation id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,_2025AND_SUCCEEDED_GET_OPERATION_ID(3)
mongoc_apm_command_succeeded_get_reply.3
MONGOC_APM_COMMAND_SUCCEEDED_GET_REPLY(3)gocAPM_COMMAND_SUCCEEDED_GET_REPLY(3)
SYNOPSIS
const bson_t *
mongoc_apm_command_succeeded_get_reply (
const mongoc_apm_command_succeeded_t *event);
Returns this event's reply. The data is only valid in the scope of the
callback that receives this event; copy it if it will be accessed after
the callback returns.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
A bson_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025PM_COMMAND_SUCCEEDED_GET_REPLY(3)
mongoc_apm_command_succeeded_get_request_id.3
MONGOC_APM_COMMAND_SUCCEEDED_GETMREQUESTnID(3)MAND_SUCCEEDED_GET_REQUEST_ID(3)
SYNOPSIS
int64_t
mongoc_apm_command_succeeded_get_request_id (
const mongoc_apm_command_succeeded_t *event);
Returns this event's wire-protocol request id. Use this number to cor-
relate client-side events with server log messages.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
The event's request id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,P2025MMAND_SUCCEEDED_GET_REQUEST_ID(3)
mongoc_apm_command_succeeded_get_server_connection_id_int64.3
MONGOC_APM_COMMANDNSUCCEEDEDOGETNSERVERoCONNECTIONEIDEINT64(3)TION_ID_INT64(3)
SYNOPSIS
int64_t
mongoc_apm_command_succeeded_get_server_connection_id_int64 (
const mongoc_apm_command_succeeded_t *event);
Returns the server connection ID for the command. The server connection
ID is distinct from the server ID (-
mongoc_apm_command_succeeded_get_server_id()) and is returned by the
hello or legacy hello response as "connectionId" from the server on
4.2+.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
The server connection ID as a positive integer or -1 if it is not
available.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_APM_COMMANMayU12,E2025GET_SERVER_CONNECTION_ID_INT64(3)
mongoc_apm_command_succeeded_get_server_id.3
MONGOC_APM_COMMAND_SUCCEEDED_GET_SERVERoID(3)OMMAND_SUCCEEDED_GET_SERVER_ID(3)
SYNOPSIS
uint32_t
mongoc_apm_command_succeeded_get_server_id (
const mongoc_apm_command_succeeded_t *event);
Returns this event's server id.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
The event's server id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,A2025OMMAND_SUCCEEDED_GET_SERVER_ID(3)
mongoc_apm_command_succeeded_get_service_id.3
MONGOC_APM_COMMAND_SUCCEEDED_GETMSERVICEnID(3)MAND_SUCCEEDED_GET_SERVICE_ID(3)
SYNOPSIS
const bson_oid_t *
mongoc_apm_command_succeeded_get_service_id (
const mongoc_apm_command_succeeded_t *event);
Returns this event's service ID, which identifies the MongoDB service
behind a load balancer, or NULL if not connected to a load balanced
cluster.
PARAMETERS
+ event: A mongoc_apm_command_succeeded_t.
RETURNS
A bson_oid_t that should not be modified or freed or NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,P2025MMAND_SUCCEEDED_GET_SERVICE_ID(3)
mongoc_apm_command_succeeded_t.3
MONGOC_APM_COMMAND_SUCCEEDED_T(3) libmongoc MONGOC_APM_COMMAND_SUCCEEDED_T(3)
Command-succeeded event
SYNOPSIS
An event notification sent when the driver successfully executes a Mon-
goDB command.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_APM_COMMAND_SUCCEEDED_T(3)
mongoc_apm_server_changed_get_context.3
MONGOC_APM_SERVER_CHANGED_GET_CONTEXT(3)ngoc_APM_SERVER_CHANGED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_server_changed_get_context (
const mongoc_apm_server_changed_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_server_changed_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025APM_SERVER_CHANGED_GET_CONTEXT(3)
mongoc_apm_server_changed_get_host.3
MONGOC_APM_SERVER_CHANGED_GET_HOST(3)bmongocGOC_APM_SERVER_CHANGED_GET_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_apm_server_changed_get_host (const mongoc_apm_server_changed_t *event);
Returns this event's host. This mongoc_host_list_t is not part of a
linked list, it is solely the server for this event. The data is only
valid in the scope of the callback that receives this event; copy it if
it will be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_server_changed_t.
RETURNS
A mongoc_host_list_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_APM_SERVER_CHANGED_GET_HOST(3)
mongoc_apm_server_changed_get_new_description.3
MONGOC_APM_SERVER_CHANGED_GET_NEWGDESCRIPTION(3)CHANGED_GET_NEW_DESCRIPTION(3)
SYNOPSIS
const mongoc_server_description_t *
mongoc_apm_server_changed_get_new_description (
const mongoc_apm_server_changed_t *event);
Returns this event's new description. The data is only valid in the
scope of the callback that receives this event; copy it if it will be
accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_server_changed_t.
RETURNS
A mongoc_server_description_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,_2025ER_CHANGED_GET_NEW_DESCRIPTION(3)
mongoc_apm_server_changed_get_previous_description.3
MONGOC_APM_SERVER_CHANGEDMGETOPREVIOUSmDESCRIPTION(3)T_PREVIOUS_DESCRIPTION(3)
SYNOPSIS
const mongoc_server_description_t *
mongoc_apm_server_changed_get_previous_description (
const mongoc_apm_server_changed_t *event);
Returns this event's previous description. The data is only valid in
the scope of the callback that receives this event; copy it if it will
be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_server_changed_t.
RETURNS
A mongoc_server_description_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_AMayS12,E2025ANGED_GET_PREVIOUS_DESCRIPTION(3)
mongoc_apm_server_changed_get_topology_id.3
MONGOC_APM_SERVER_CHANGED_GET_TOPOLOGYmID(3)_SERVER_CHANGED_GET_TOPOLOGY_ID(3)
SYNOPSIS
void
mongoc_apm_server_changed_get_topology_id (
const mongoc_apm_server_changed_t *event, bson_oid_t *topology_id);
Returns this event's topology id.
PARAMETERS
+ event: A mongoc_apm_server_changed_t.
+ topology_id: A bson_oid_t to receive the event's topology_id.
RETURNS
The event's topology id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025SERVER_CHANGED_GET_TOPOLOGY_ID(3)
mongoc_apm_server_changed_t.3
MONGOC_APM_SERVER_CHANGED_T(3) libmongoc MONGOC_APM_SERVER_CHANGED_T(3)
Server-changed event
SYNOPSIS
An event notification sent when the driver observes a change in status
of a server it is connected to.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_SERVER_CHANGED_T(3)
mongoc_apm_server_closed_get_context.3
MONGOC_APM_SERVER_CLOSED_GET_CONTEXT(3)ongocC_APM_SERVER_CLOSED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_server_closed_get_context (const mongoc_apm_server_closed_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_server_closed_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_APM_SERVER_CLOSED_GET_CONTEXT(3)
mongoc_apm_server_closed_get_host.3
MONGOC_APM_SERVER_CLOSED_GET_HOST(3)ibmongocNGOC_APM_SERVER_CLOSED_GET_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_apm_server_closed_get_host (const mongoc_apm_server_closed_t *event);
Returns this event's host. This mongoc_host_list_t is not part of a
linked list, it is solely the server for this event. The data is only
valid in the scope of the callback that receives this event; copy it if
it will be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_server_closed_t.
RETURNS
A mongoc_host_list_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_APM_SERVER_CLOSED_GET_HOST(3)
mongoc_apm_server_closed_get_topology_id.3
MONGOC_APM_SERVER_CLOSED_GET_TOPOLOGYbID(3)cM_SERVER_CLOSED_GET_TOPOLOGY_ID(3)
SYNOPSIS
void
mongoc_apm_server_closed_get_topology_id (
const mongoc_apm_server_closed_t *event, bson_oid_t *topology_id);
Returns this event's topology id.
PARAMETERS
+ event: A mongoc_apm_server_closed_t.
+ topology_id: A bson_oid_t to receive the event's topology_id.
RETURNS
The event's topology id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025_SERVER_CLOSED_GET_TOPOLOGY_ID(3)
mongoc_apm_server_closed_t.3
MONGOC_APM_SERVER_CLOSED_T(3) libmongoc MONGOC_APM_SERVER_CLOSED_T(3)
Server-closed event
SYNOPSIS
An event notification sent when the driver stops monitoring a server
and removes its mongoc_server_description_t.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_SERVER_CLOSED_T(3)
mongoc_apm_server_heartbeat_failed_get_awaited.3
MONGOC_APM_SERVER_HEARTBEAT_FAILEDCGETmAWAITED(3)ARTBEAT_FAILED_GET_AWAITED(3)
SYNOPSIS
bool
mongoc_apm_server_heartbeat_failed_get_awaited (
const mongoc_apm_server_heartbeat_failed_t *event);
Returns whether this event came from an awaitable hello.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_failed_t.
RETURNS
A bool indicating whether the heartbeat event came from an awaitable
hello.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayA12,S2025R_HEARTBEAT_FAILED_GET_AWAITED(3)
mongoc_apm_server_heartbeat_failed_get_context.3
MONGOC_APM_SERVER_HEARTBEAT_FAILEDCGETmCONTEXT(3)ARTBEAT_FAILED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_server_heartbeat_failed_get_context (
const mongoc_apm_server_heartbeat_failed_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_failed_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayA12,S2025R_HEARTBEAT_FAILED_GET_CONTEXT(3)
mongoc_apm_server_heartbeat_failed_get_duration.3
MONGOC_APM_SERVER_HEARTBEAT_FAILED_GETmDURATION(3)TBEAT_FAILED_GET_DURATION(3)
SYNOPSIS
int64_t
mongoc_apm_server_heartbeat_failed_get_duration (
const mongoc_apm_server_heartbeat_failed_t *event);
Returns this event's duration in microseconds.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_failed_t.
RETURNS
The event's duration.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayP12,E2025_HEARTBEAT_FAILED_GET_DURATION(3)
mongoc_apm_server_heartbeat_failed_get_error.3
MONGOC_APM_SERVER_HEARTBEAT_FAILEDGGETmERROR(3)R_HEARTBEAT_FAILED_GET_ERROR(3)
SYNOPSIS
void
mongoc_apm_server_heartbeat_failed_get_error (
const mongoc_apm_server_heartbeat_failed_t *event, bson_error_t *error);
Copies this event's error info.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_failed_t.
+ error: A bson_error_t to receive the event's error info.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,M2025VER_HEARTBEAT_FAILED_GET_ERROR(3)
mongoc_apm_server_heartbeat_failed_get_host.3
MONGOC_APM_SERVER_HEARTBEAT_FAILEDNGETmHOST(3)VER_HEARTBEAT_FAILED_GET_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_apm_server_heartbeat_failed_get_host (
const mongoc_apm_server_heartbeat_failed_t *event);
Returns this event's host. This mongoc_host_list_t is not part of a
linked list, it is solely the server for this event. The data is only
valid in the scope of the callback that receives this event; copy it if
it will be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_failed_t.
RETURNS
A mongoc_host_list_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,P2025RVER_HEARTBEAT_FAILED_GET_HOST(3)
mongoc_apm_server_heartbeat_failed_t.3
MONGOC_APM_SERVER_HEARTBEAT_FAILED_T(3)ongocC_APM_SERVER_HEARTBEAT_FAILED_T(3)
Heartbeat-failed event
SYNOPSIS
An event notification sent when the driver failed to send a "hello"
command to check the status of a server.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_APM_SERVER_HEARTBEAT_FAILED_T(3)
mongoc_apm_server_heartbeat_started_get_awaited.3
MONGOC_APM_SERVER_HEARTBEAT_STARTEDlGEToAWAITED(3)TBEAT_STARTED_GET_AWAITED(3)
SYNOPSIS
bool
mongoc_apm_server_heartbeat_started_get_awaited (
const mongoc_apm_server_heartbeat_started_t *event);
Returns whether this event came from an awaitable hello.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_started_t.
RETURNS
A bool indicating whether the heartbeat event came from an awaitable
hello.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayP12,E2025_HEARTBEAT_STARTED_GET_AWAITED(3)
mongoc_apm_server_heartbeat_started_get_context.3
MONGOC_APM_SERVER_HEARTBEAT_STARTEDlGEToCONTEXT(3)TBEAT_STARTED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_server_heartbeat_started_get_context (
const mongoc_apm_server_heartbeat_started_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_started_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayP12,E2025_HEARTBEAT_STARTED_GET_CONTEXT(3)
mongoc_apm_server_heartbeat_started_get_host.3
MONGOC_APM_SERVER_HEARTBEAT_STARTEDlGEToHOST(3)R_HEARTBEAT_STARTED_GET_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_apm_server_heartbeat_started_get_host (
const mongoc_apm_server_heartbeat_started_t *event);
Returns this event's host. This mongoc_host_list_t is not part of a
linked list, it is solely the server for this event. The data is only
valid in the scope of the callback that receives this event; copy it if
it will be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_started_t.
RETURNS
A mongoc_host_list_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,M2025VER_HEARTBEAT_STARTED_GET_HOST(3)
mongoc_apm_server_heartbeat_started_t.3
MONGOC_APM_SERVER_HEARTBEAT_STARTEDlT(3)ngoc_APM_SERVER_HEARTBEAT_STARTED_T(3)
Heartbeat-started event
SYNOPSIS
An event notification sent when the driver begins executing a "hello"
command to check the status of a server.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025APM_SERVER_HEARTBEAT_STARTED_T(3)
mongoc_apm_server_heartbeat_succeeded_get_awaited.3
MONGOC_APM_SERVER_HEARTBEATOSUCCEEDEDbGETgAWAITED(3)T_SUCCEEDED_GET_AWAITED(3)
SYNOPSIS
bool
mongoc_apm_server_heartbeat_succeeded_get_awaited (
const mongoc_apm_server_heartbeat_succeeded_t *event);
Returns whether this event came from an awaitable hello.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_succeeded_t.
RETURNS
A bool indicating whether the heartbeat event came from an awaitable
hello.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_May_12,V2025EARTBEAT_SUCCEEDED_GET_AWAITED(3)
mongoc_apm_server_heartbeat_succeeded_get_context.3
MONGOC_APM_SERVER_HEARTBEATOSUCCEEDEDbGETgCONTEXT(3)T_SUCCEEDED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_server_heartbeat_succeeded_get_context (
const mongoc_apm_server_heartbeat_succeeded_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_succeeded_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_May_12,V2025EARTBEAT_SUCCEEDED_GET_CONTEXT(3)
mongoc_apm_server_heartbeat_succeeded_get_duration.3
MONGOC_APM_SERVER_HEARTBEATNSUCCEEDEDbGETgDURATION(3)SUCCEEDED_GET_DURATION(3)
SYNOPSIS
int64_t
mongoc_apm_server_heartbeat_succeeded_get_duration (
const mongoc_apm_server_heartbeat_succeeded_t *event);
Returns this event's duration in microseconds.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_succeeded_t.
RETURNS
The event's duration.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_AMayS12,E2025ARTBEAT_SUCCEEDED_GET_DURATION(3)
mongoc_apm_server_heartbeat_succeeded_get_host.3
MONGOC_APM_SERVER_HEARTBEAT_SUCCEEDEDbGETgHOST(3)ARTBEAT_SUCCEEDED_GET_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_apm_server_heartbeat_succeeded_get_host (
const mongoc_apm_server_heartbeat_succeeded_t *event);
Returns this event's host. This mongoc_host_list_t is not part of a
linked list, it is solely the server for this event. The data is only
valid in the scope of the callback that receives this event; copy it if
it will be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_succeeded_t.
RETURNS
A mongoc_host_list_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayA12,S2025R_HEARTBEAT_SUCCEEDED_GET_HOST(3)
mongoc_apm_server_heartbeat_succeeded_get_reply.3
MONGOC_APM_SERVER_HEARTBEAT_SUCCEEDEDbGETgREPLY(3)TBEAT_SUCCEEDED_GET_REPLY(3)
SYNOPSIS
const bson_t *
mongoc_apm_server_heartbeat_succeeded_get_reply (
const mongoc_apm_server_heartbeat_succeeded_t *event);
Returns this event's reply. The data is only valid in the scope of the
callback that receives this event; copy it if it will be accessed after
the callback returns.
PARAMETERS
+ event: A mongoc_apm_server_heartbeat_succeeded_t.
RETURNS
A bson_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayP12,E2025_HEARTBEAT_SUCCEEDED_GET_REPLY(3)
mongoc_apm_server_heartbeat_succeeded_t.3
MONGOC_APM_SERVER_HEARTBEAT_SUCCEEDEDbT(3)ocPM_SERVER_HEARTBEAT_SUCCEEDED_T(3)
Heartbeat-succeeded event
SYNOPSIS
An event notification sent when the driver completes a "hello" command
to check the status of a server.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025M_SERVER_HEARTBEAT_SUCCEEDED_T(3)
mongoc_apm_server_opening_get_context.3
MONGOC_APM_SERVER_OPENING_GET_CONTEXT(3)ngoc_APM_SERVER_OPENING_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_server_opening_get_context (
const mongoc_apm_server_opening_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_server_opening_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025APM_SERVER_OPENING_GET_CONTEXT(3)
mongoc_apm_server_opening_get_host.3
MONGOC_APM_SERVER_OPENING_GET_HOST(3)bmongocGOC_APM_SERVER_OPENING_GET_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_apm_server_opening_get_host (const mongoc_apm_server_opening_t *event);
Returns this event's host. This mongoc_host_list_t is not part of a
linked list, it is solely the server for this event. The data is only
valid in the scope of the callback that receives this event; copy it if
it will be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_server_opening_t.
RETURNS
A mongoc_host_list_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_APM_SERVER_OPENING_GET_HOST(3)
mongoc_apm_server_opening_get_topology_id.3
MONGOC_APM_SERVER_OPENING_GET_TOPOLOGYmID(3)_SERVER_OPENING_GET_TOPOLOGY_ID(3)
SYNOPSIS
void
mongoc_apm_server_opening_get_topology_id (
const mongoc_apm_server_opening_t *event, bson_oid_t *topology_id);
Returns this event's topology id.
PARAMETERS
+ event: A mongoc_apm_server_opening_t.
+ topology_id: A bson_oid_t to receive the event's topology_id.
RETURNS
The event's topology id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025SERVER_OPENING_GET_TOPOLOGY_ID(3)
mongoc_apm_server_opening_t.3
MONGOC_APM_SERVER_OPENING_T(3) libmongoc MONGOC_APM_SERVER_OPENING_T(3)
Server-opening event
SYNOPSIS
An event notification sent when the driver adds a
mongoc_server_description_t for a new server it was not monitoring be-
fore.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_SERVER_OPENING_T(3)
mongoc_apm_set_command_failed_cb.3
MONGOC_APM_SET_COMMAND_FAILED_CB(3)libmongocONGOC_APM_SET_COMMAND_FAILED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_command_failed_cb_t) (
const mongoc_apm_command_failed_t *event);
void
mongoc_apm_set_command_failed_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_command_failed_cb_t cb);
Receive an event notification whenever the driver fails to execute a
MongoDB operation.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_command_failed_t whenever a
MongoDB operation fails.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_APM_SET_COMMAND_FAILED_CB(3)
mongoc_apm_set_command_started_cb.3
MONGOC_APM_SET_COMMAND_STARTED_CB(3)ibmongocNGOC_APM_SET_COMMAND_STARTED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_command_started_cb_t) (
const mongoc_apm_command_started_t *event);
void
mongoc_apm_set_command_started_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_command_started_cb_t cb);
Receive an event notification whenever the driver starts a MongoDB op-
eration.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_command_started_t whenever
the driver begins a MongoDB operation.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_APM_SET_COMMAND_STARTED_CB(3)
mongoc_apm_set_command_succeeded_cb.3
MONGOC_APM_SET_COMMAND_SUCCEEDED_CB(3)mongocOC_APM_SET_COMMAND_SUCCEEDED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_command_succeeded_cb_t) (
const mongoc_apm_command_succeeded_t *event);
void
mongoc_apm_set_command_succeeded_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_command_succeeded_cb_t cb);
Receive an event notification whenever the driver completes a MongoDB
operation.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_command_succeeded_t whenever
the driver completes a MongoDB operation.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_APM_SET_COMMAND_SUCCEEDED_CB(3)
mongoc_apm_set_server_changed_cb.3
MONGOC_APM_SET_SERVER_CHANGED_CB(3)libmongocONGOC_APM_SET_SERVER_CHANGED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_server_changed_cb_t) (
const mongoc_apm_server_changed_t *event);
void
mongoc_apm_set_server_changed_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_server_changed_cb_t cb);
Receive an event notification whenever the driver observes a change in
status of a server it is connected to.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_server_changed_t whenever
the driver observes a change in status of a server it is connected
to.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_APM_SET_SERVER_CHANGED_CB(3)
mongoc_apm_set_server_closed_cb.3
MONGOC_APM_SET_SERVER_CLOSED_CB(3) libmongocMONGOC_APM_SET_SERVER_CLOSED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_server_closed_cb_t) (
const mongoc_apm_server_closed_t *event);
void
mongoc_apm_set_server_closed_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_server_closed_cb_t cb);
Receive an event notification whenever the driver stops monitoring a
server and removes its mongoc_server_description_t.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_server_closed_t whenever the
driver stops monitoring a server and removes its
mongoc_server_description_t.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_APM_SET_SERVER_CLOSED_CB(3)
mongoc_apm_set_server_heartbeat_failed_cb.3
MONGOC_APM_SET_SERVER_HEARTBEAT_FAILEDmCB(3)_SET_SERVER_HEARTBEAT_FAILED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_server_heartbeat_failed_cb_t) (
const mongoc_apm_server_heartbeat_failed_t *event);
void
mongoc_apm_set_server_heartbeat_failed_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_server_heartbeat_failed_cb_t cb);
Receive an event notification whenever the driver fails to send a
"hello" command to check the status of a server.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_server_heartbeat_failed_t
whenever the driver fails to send a "hello" command to check the sta-
tus of a server.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025SET_SERVER_HEARTBEAT_FAILED_CB(3)
mongoc_apm_set_server_heartbeat_started_cb.3
MONGOC_APM_SET_SERVER_HEARTBEAT_STARTEDoCB(3)ET_SERVER_HEARTBEAT_STARTED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_server_heartbeat_started_cb_t) (
const mongoc_apm_server_heartbeat_started_t *event);
void
mongoc_apm_set_server_heartbeat_started_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_server_heartbeat_started_cb_t cb);
Receive an event notification whenever the driver begins executing a
"hello" command to check the status of a server.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_server_heartbeat_started_t
whenever the driver begins executing a "hello" command to check the
status of a server.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,A2025ET_SERVER_HEARTBEAT_STARTED_CB(3)
mongoc_apm_set_server_heartbeat_succeeded_cb.3
MONGOC_APM_SET_SERVER_HEARTBEATMSUCCEEDEDgCB(3)ERVER_HEARTBEAT_SUCCEEDED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_server_heartbeat_succeeded_cb_t) (
const mongoc_apm_server_heartbeat_succeeded_t *event);
void
mongoc_apm_set_server_heartbeat_succeeded_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_server_heartbeat_succeeded_cb_t cb);
Receive an event notification whenever the driver completes a "hello"
command to check the status of a server.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_server_heartbeat_succeeded_t
whenever the driver completes a "hello" command to check the status
of a server.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,M2025_SERVER_HEARTBEAT_SUCCEEDED_CB(3)
mongoc_apm_set_server_opening_cb.3
MONGOC_APM_SET_SERVER_OPENING_CB(3)libmongocONGOC_APM_SET_SERVER_OPENING_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_server_opening_cb_t) (
const mongoc_apm_server_opening_t *event);
void
mongoc_apm_set_server_opening_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_server_opening_cb_t cb);
Receive an event notification whenever the driver adds a
mongoc_server_description_t for a new server it was not monitoring be-
fore.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_server_opening_t whenever
the driver adds a mongoc_server_description_t for a new server it was
not monitoring before.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_APM_SET_SERVER_OPENING_CB(3)
mongoc_apm_set_topology_changed_cb.3
MONGOC_APM_SET_TOPOLOGY_CHANGED_CB(3)bmongocGOC_APM_SET_TOPOLOGY_CHANGED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_topology_changed_cb_t) (
const mongoc_apm_topology_changed_t *event);
void
mongoc_apm_set_topology_changed_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_topology_changed_cb_t cb);
Receive an event notification whenever the driver observes a change in
any of the servers it is connected to or a change in the overall server
topology.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_topology_changed_t whenever
the driver observes a change in any of the servers it is connected to
or a change in the overall server topology.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_APM_SET_TOPOLOGY_CHANGED_CB(3)
mongoc_apm_set_topology_closed_cb.3
MONGOC_APM_SET_TOPOLOGY_CLOSED_CB(3)ibmongocNGOC_APM_SET_TOPOLOGY_CLOSED_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_topology_closed_cb_t) (
const mongoc_apm_topology_closed_t *event);
void
mongoc_apm_set_topology_closed_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_topology_closed_cb_t cb);
Receive an event notification whenever the driver stops monitoring a
server topology and destroys its mongoc_topology_description_t.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_topology_closed_t whenever
the driver stops monitoring a server topology and destroys its
mongoc_topology_description_t.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_APM_SET_TOPOLOGY_CLOSED_CB(3)
mongoc_apm_set_topology_opening_cb.3
MONGOC_APM_SET_TOPOLOGY_OPENING_CB(3)bmongocGOC_APM_SET_TOPOLOGY_OPENING_CB(3)
SYNOPSIS
typedef void (*mongoc_apm_topology_opening_cb_t) (
const mongoc_apm_topology_opening_t *event);
void
mongoc_apm_set_topology_opening_cb (mongoc_apm_callbacks_t *callbacks,
mongoc_apm_topology_opening_cb_t cb);
Receive an event notification whenever the driver initializes a
mongoc_topology_description_t.
PARAMETERS
+ callbacks: A mongoc_apm_callbacks_t.
+ cb: A function to call with a mongoc_apm_topology_opening_t whenever
the driver initializes a mongoc_topology_description_t.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_APM_SET_TOPOLOGY_OPENING_CB(3)
mongoc_apm_topology_changed_get_context.3
MONGOC_APM_TOPOLOGY_CHANGED_GET_CONTEXT(3)ocPM_TOPOLOGY_CHANGED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_topology_changed_get_context (
const mongoc_apm_topology_changed_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_topology_changed_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025M_TOPOLOGY_CHANGED_GET_CONTEXT(3)
mongoc_apm_topology_changed_get_new_description.3
MONGOC_APM_TOPOLOGY_CHANGED_GETGNEWlDESCRIPTION(3)ANGED_GET_NEW_DESCRIPTION(3)
SYNOPSIS
const mongoc_topology_description_t *
mongoc_apm_topology_changed_get_new_description (
const mongoc_apm_topology_changed_t *event);
Returns this event's new description. The data is only valid in the
scope of the callback that receives this event; copy it if it will be
accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_topology_changed_t.
RETURNS
A mongoc_topology_description_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayP12,O2025GY_CHANGED_GET_NEW_DESCRIPTION(3)
mongoc_apm_topology_changed_get_previous_description.3
MONGOC_APM_TOPOLOGY_CHANGEDOGETPPREVIOUSnDESCRIPTION(3)PREVIOUS_DESCRIPTION(3)
SYNOPSIS
const mongoc_topology_description_t *
mongoc_apm_topology_changed_get_previous_description (
const mongoc_apm_topology_changed_t *event);
Returns this event's previous description. The data is only valid in
the scope of the callback that receives this event; copy it if it will
be accessed after the callback returns.
PARAMETERS
+ event: A mongoc_apm_topology_changed_t.
RETURNS
A mongoc_topology_description_t that should not be modified or freed.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_APMMayP12,G2025ANGED_GET_PREVIOUS_DESCRIPTION(3)
mongoc_apm_topology_changed_get_topology_id.3
MONGOC_APM_TOPOLOGY_CHANGED_GET_TOPOLOGYnID(3)OLOGY_CHANGED_GET_TOPOLOGY_ID(3)
SYNOPSIS
void
mongoc_apm_topology_changed_get_topology_id (
const mongoc_apm_topology_changed_t *event, bson_oid_t *topology_id);
Returns this event's topology id.
PARAMETERS
+ event: A mongoc_apm_topology_changed_t.
+ topology_id: A bson_oid_t to receive the event's topology_id.
RETURNS
The event's topology id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,P2025POLOGY_CHANGED_GET_TOPOLOGY_ID(3)
mongoc_apm_topology_changed_t.3
MONGOC_APM_TOPOLOGY_CHANGED_T(3) libmongoc MONGOC_APM_TOPOLOGY_CHANGED_T(3)
Topology-changed event
SYNOPSIS
An event notification sent when the driver observes a change in any of
the servers it is connected to or a change in the overall server topol-
ogy.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_TOPOLOGY_CHANGED_T(3)
mongoc_apm_topology_closed_get_context.3
MONGOC_APM_TOPOLOGY_CLOSED_GET_CONTEXT(3)gocAPM_TOPOLOGY_CLOSED_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_topology_closed_get_context (
const mongoc_apm_topology_closed_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_topology_closed_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025PM_TOPOLOGY_CLOSED_GET_CONTEXT(3)
mongoc_apm_topology_closed_get_topology_id.3
MONGOC_APM_TOPOLOGY_CLOSED_GET_TOPOLOGYoID(3)OPOLOGY_CLOSED_GET_TOPOLOGY_ID(3)
SYNOPSIS
void
mongoc_apm_topology_closed_get_topology_id (
const mongoc_apm_topology_closed_t *event, bson_oid_t *topology_id);
Returns this event's topology id.
PARAMETERS
+ event: A mongoc_apm_topology_closed_t.
+ topology_id: A bson_oid_t to receive the event's topology_id.
RETURNS
The event's topology id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,A2025OPOLOGY_CLOSED_GET_TOPOLOGY_ID(3)
mongoc_apm_topology_closed_t.3
MONGOC_APM_TOPOLOGY_CLOSED_T(3) libmongoc MONGOC_APM_TOPOLOGY_CLOSED_T(3)
Topology-closed event
SYNOPSIS
An event notification sent when the driver stops monitoring a server
topology and destroys its mongoc_topology_description_t.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_TOPOLOGY_CLOSED_T(3)
mongoc_apm_topology_opening_get_context.3
MONGOC_APM_TOPOLOGY_OPENING_GET_CONTEXT(3)ocPM_TOPOLOGY_OPENING_GET_CONTEXT(3)
SYNOPSIS
void *
mongoc_apm_topology_opening_get_context (
const mongoc_apm_topology_opening_t *event);
Returns this event's context.
PARAMETERS
+ event: A mongoc_apm_topology_opening_t.
RETURNS
The pointer passed with mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025M_TOPOLOGY_OPENING_GET_CONTEXT(3)
mongoc_apm_topology_opening_get_topology_id.3
MONGOC_APM_TOPOLOGY_OPENING_GET_TOPOLOGYnID(3)OLOGY_OPENING_GET_TOPOLOGY_ID(3)
SYNOPSIS
void
mongoc_apm_topology_opening_get_topology_id (
const mongoc_apm_topology_opening_t *event, bson_oid_t *topology_id);
Returns this event's topology id.
PARAMETERS
+ event: A mongoc_apm_topology_opening_t.
+ topology_id: A bson_oid_t to receive the event's topology_id.
RETURNS
The event's topology id.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,P2025POLOGY_OPENING_GET_TOPOLOGY_ID(3)
mongoc_apm_topology_opening_t.3
MONGOC_APM_TOPOLOGY_OPENING_T(3) libmongoc MONGOC_APM_TOPOLOGY_OPENING_T(3)
Topology-opening event
SYNOPSIS
An event notification sent when the driver initializes a
mongoc_topology_description_t.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_APM_TOPOLOGY_OPENING_T(3)
mongoc_application_performance_monitoring.3
MONGOC_APPLICATION_PERFORMANCE_MONITORING(3)LICATION_PERFORMANCE_MONITORING(3)
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:
+ Command Logging and Monitoring: events related to all application op-
erations.
+ SDAM Monitoring: events related to the driver's Server Discovery And
Monitoring logic.
To receive notifications, create a mongoc_apm_callbacks_t with
mongoc_apm_callbacks_new(), set callbacks on it, then pass it to
mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
COMMAND-MONITORING EXAMPLE
example-command-monitoring.c
/* 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: %s\n"
"error message: %s\n",
uri_string,
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;
}
This example program prints:
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
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.
The final "insert" command is considered successful, despite the
writeError, because the server replied to the overall command with
"ok": 1.
SDAM MONITORING EXAMPLE
example-sdam-monitoring.c
/* 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);
}
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);
}
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");
}
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);
}
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: %s\n"
"error message: %s\n",
uri_string,
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;
}
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 discov-
ers the third member, "localhost:27019", and adds it to the topology.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025ICATION_PERFORMANCE_MONITORING(3)
mongoc_auto_encryption_opts_destroy.3
MONGOC_AUTO_ENCRYPTION_OPTS_DESTROY(3)mongocOC_AUTO_ENCRYPTION_OPTS_DESTROY(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_destroy (mongoc_auto_encryption_opts_t *opts);
Destroy a mongoc_auto_encryption_opts_t.
PARAMETERS
+ opts The mongoc_auto_encryption_opts_t to destroy.
SEE ALSO:
mongoc_auto_encryption_opts_new()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_AUTO_ENCRYPTION_OPTS_DESTROY(3)
mongoc_auto_encryption_opts_new.3
MONGOC_AUTO_ENCRYPTION_OPTS_NEW(3) libmongocMONGOC_AUTO_ENCRYPTION_OPTS_NEW(3)
SYNOPSIS
mongoc_auto_encryption_opts_t *
mongoc_auto_encryption_opts_new (void);
Create a new mongoc_auto_encryption_opts_t.
Caller must set the required options:
+ mongoc_auto_encryption_opts_set_keyvault_namespace()
+ mongoc_auto_encryption_opts_set_kms_providers()
Caller may set optionally set the following:
+ mongoc_auto_encryption_opts_set_keyvault_client()
+ mongoc_auto_encryption_opts_set_schema_map()
+ mongoc_auto_encryption_opts_set_bypass_auto_encryption()
+ mongoc_auto_encryption_opts_set_extra()
This options struct is used to enable auto encryption with
mongoc_client_enable_auto_encryption().
RETURNS
A new mongoc_auto_encryption_opts_t, which must be destroyed with
mongoc_auto_encryption_opts_destroy().
SEE ALSO:
mongoc_auto_encryption_opts_destroy()
mongoc_client_enable_auto_encryption()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_AUTO_ENCRYPTION_OPTS_NEW(3)
mongoc_auto_encryption_opts_set_bypass_auto_encryption.3
MONGOC_AUTO_ENCRYPTIONOOPTS_SETOBYPASSmAUTOcENCRYPTION(3)SS_AUTO_ENCRYPTION(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_bypass_auto_encryption (
mongoc_auto_encryption_opts_t *opts, bool bypass_auto_encryption);
PARAMETERS
+ opts: The mongoc_auto_encryption_opts_t
+ bypass_auto_encryption: A boolean. If true, a mongoc_client_t config-
ured with mongoc_client_enable_auto_encryption() will only perform
automatic decryption (not encryption).
SEE ALSO:
mongoc_client_enable_auto_encryption()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_AUTO_MayR12,I2025PTS_SET_BYPASS_AUTO_ENCRYPTION(3)
mongoc_auto_encryption_opts_set_bypass_query_analysis.3
MONGOC_AUTO_ENCRYPTIONMOPTSCSETTBYPASSmQUERY_ANALYSIS(3)PASS_QUERY_ANALYSIS(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_bypass_query_analysis (
mongoc_auto_encryption_opts_t *opts, bool bypass_query_analysis);
New in version 1.22.0.
PARAMETERS
+ opts: The mongoc_auto_encryption_opts_t
+ bypass_query_analysis: A boolean.
bypass_query_analysis disables automatic analysis of outgoing commands.
bypass_query_analysis is useful for encrypting indexed fields without
the crypt_shared library or mongocryptd process. Set by-
pass_query_analysis to true to use explicit encryption on indexed
fields.
SEE ALSO:
mongoc_client_enable_auto_encryption()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_AUTOMayC12,T2025OPTS_SET_BYPASS_QUERY_ANALYSIS(3)
mongoc_auto_encryption_opts_set_encrypted_fields_map.3
MONGOC_AUTO_ENCRYPTION_OPTSOSETUENCRYPTEDgFIELDSTMAP(3)ENCRYPTED_FIELDS_MAP(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_encrypted_fields_map (
mongoc_auto_encryption_opts_t *opts, const bson_t *encrypted_fields_map);
New in version 1.22.0.
PARAMETERS
+ opts: The mongoc_auto_encryption_opts_t
+ encrypted_fields_map: A bson_t where keys are collection namespaces
and values are encrypted fields documents.
Supplying an encrypted_fields_map provides more security than relying
on an encryptedFields obtained from the server. It protects against a
malicious server advertising a false encryptedFields.
The schema map does not apply to collections encrypted with: Queryable
Encryption. See mongoc_auto_encryption_opts_set_schema_map() instead.
SEE ALSO:
mongoc_client_enable_auto_encryption()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_AUTMayN12,P2025_OPTS_SET_ENCRYPTED_FIELDS_MAP(3)
mongoc_auto_encryption_opts_set_extra.3
MONGOC_AUTO_ENCRYPTION_OPTS_SET_EXTRA(3)ngoc_AUTO_ENCRYPTION_OPTS_SET_EXTRA(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_extra (mongoc_auto_encryption_opts_t *opts,
const bson_t *extra);
PARAMETERS
+ opts: The mongoc_auto_encryption_opts_t
+ extra: A bson_t of additional options.
extra is a bson_t containing any of the following optional fields:
+ mongocryptdURI set to a URI to connect to the mongocryptd process
(default is "mongodb://localhost:27020").
+ mongocryptdBypassSpawn set to true to prevent the driver from spawn-
ing the mongocryptd process (default behavior is to spawn).
+ mongocryptdSpawnPath set to a path (with trailing slash) to search
for mongocryptd (defaults to empty string and uses default system
paths).
+ mongocryptdSpawnArgs set to an array of string arguments to pass to
mongocryptd when spawning (defaults to [ "--idleShutdownTimeout-
Secs=60" ]).
+ cryptSharedLibPath - Set a filepath string referring to a
crypt_shared library file. Unset by default.
+ If not set (the default), libmongocrypt will attempt to load
crypt_shared using the host system's default dynamic-library-search
system.
+ If set, the given path should identify the crypt_shared dynamic li-
brary file itself, not the directory that contains it.
+ If the given path is a relative path and the first path component
is $ORIGIN, the $ORIGIN component will be replaced with the abso-
lute path to the directory containing the libmongocrypt library in
use by the application.
NOTE:
No other RPATH/RUNPATH-style substitutions are available.
+ If the given path is a relative path, the path will be resolved
relative to the working directory of the operating system process.
+ If this option is set and libmongocrypt fails to load crypt_shared
from the given filepath, libmongocrypt will fail to initialize and
will not attempt to search for crypt_shared in any other locations.
+ cryptSharedLibRequired - If set to true, and libmongocrypt fails to
load a crypt_shared library, initialization of auto-encryption will
fail immediately and will not attempt to spawn mongocryptd.
If set to false (the default), cryptSharedLibPath is not set, and
libmongocrypt fails to load crypt_shared, then libmongocrypt will
proceed without crypt_shared and fall back to using mongocryptd.
SEE ALSO:
mongoc_client_enable_auto_encryption()
In-Use Encryption
MongoDB Manual documentation for crypt_shared: Automatic Encryption Shared Library
MongoDB Manual documentation for mongocryptd: Install and Configure mongocryptd
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025AUTO_ENCRYPTION_OPTS_SET_EXTRA(3)
mongoc_auto_encryption_opts_set_key_expiration.3
MONGOC_AUTO_ENCRYPTION_OPTS_SETNKEYlEXPIRATION(3)ON_OPTS_SET_KEY_EXPIRATION(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_key_expiration (
mongoc_auto_encryption_opts_t *opts, uint64_t cache_expiration_ms);
PARAMETERS
+ opts: The mongoc_auto_encryption_opts_t
+ cache_expiration_ms: The data encryption key cache expiration time in
milliseconds. Defaults to 60,000. 0 means "never expire".
SEE ALSO:
mongoc_client_enable_auto_encryption()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayA12,_2025YPTION_OPTS_SET_KEY_EXPIRATION(3)
mongoc_auto_encryption_opts_set_key_vault_client.3
MONGOC_AUTO_ENCRYPTION_OPTSMSETOKEYlVAULTgCLIENT(3)PTS_SET_KEY_VAULT_CLIENT(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_keyvault_client (
mongoc_auto_encryption_opts_t *opts, mongoc_client_t *client);
Set an optional separate mongoc_client_t to use during key lookup for
automatic encryption and decryption. Only applies to automatic encryp-
tion on a single-threaded mongoc_client_t.
PARAMETERS
+ opts: A mongoc_auto_encryption_opts_t.
+ client: A mongoc_client_t to use for key queries. This client should
not have automatic encryption enabled, as it will only execute find
commands against the key vault collection to retrieve keys for auto-
matic encryption and decryption. This client MUST outlive any
mongoc_client_t which has been enabled to use it through
mongoc_client_enable_auto_encryption().
SEE ALSO:
mongoc_client_enable_auto_encryption()
mongoc_auto_encryption_opts_set_keyvault_client_pool()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOCMayT12,N2025TION_OPTS_SET_KEY_VAULT_CLIENT(3)
mongoc_auto_encryption_opts_set_key_vault_client_pool.3
MONGOC_AUTO_ENCRYPTIONMOPTSCSETTKEYlVAULTgCLIENTSPOOL(3)Y_VAULT_CLIENT_POOL(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_keyvault_client_pool (
mongoc_auto_encryption_opts_t *opts, mongoc_client_pool_t *pool);
Set an optional separate mongoc_client_pool_t to use during key lookup
for automatic encryption and decryption. Only applies to automatic en-
cryption on a mongoc_client_pool_t. It is invalid to set this for auto-
matic encryption on a single-threaded mongoc_client_t.
PARAMETERS
+ opts: A mongoc_auto_encryption_opts_t.
+ pool: A mongoc_client_pool_t to use for key queries. This client pool
should not have automatic encryption enabled, as it will only execute
find commands against the key vault collection to retrieve keys for
automatic encryption and decryption. This pool MUST outlive any
mongoc_client_pool_t which has been enabled to use it through
mongoc_client_pool_enable_auto_encryption().
SEE ALSO:
mongoc_client_pool_enable_auto_encryption()
mongoc_auto_encryption_opts_set_keyvault_client()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_AUTOMayC12,T2025OPTS_SET_KEY_VAULT_CLIENT_POOL(3)
mongoc_auto_encryption_opts_set_key_vault_namespace.3
MONGOC_AUTO_ENCRYPTION_OPTSGSETAKEYlVAULTgNAMESPACE(3)T_KEY_VAULT_NAMESPACE(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_keyvault_namespace (
mongoc_auto_encryption_opts_t *opts, const char *db, const char *coll);
Set the database and collection name of the key vault. The key vault is
the specially designated collection containing encrypted data keys for
In-Use Encryption.
PARAMETERS
+ opts: The mongoc_auto_encryption_opts_t
+ db: A const char * representing the database name of the key vault
collection.
+ coll: A const char * representing the collection name of the key
vault collection.
SEE ALSO:
mongoc_client_enable_auto_encryption()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_AUMayE12,Y2025N_OPTS_SET_KEY_VAULT_NAMESPACE(3)
mongoc_auto_encryption_opts_set_kms_credential_provider_callback.3
MONGOC_AUTOMENCRYPTION_OPTSYSETOKMSlCREDENTIAL_PROVIDERACALLBACK(3)CALLBACK(3)
New in version 1.23.0.
SYNOPSIS
void
mongoc_auto_encryption_opts_set_kms_credential_provider_callback(
mongoc_auto_encryption_opts_t *opts,
mongoc_kms_credentials_provider_callback_fn fn,
void *userdata);
Set the user-provided callback to provide KMS credentials on-demand
when they are needed.
PARAMETERS
+ opts - The options object to update.
+ fn - The provider callback to set on the options object. May be NULL
to clear the callback. Refer to:
mongoc_kms_credentials_provider_callback_fn
+ userdata - An arbitrary pointer that will be passed along to the
callback function when it is called by libmongoc.
SEE ALSO:
mongoc_client_encryption_opts_set_kms_credential_provider_callback
()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_AUTO_ENCRYPTIONMayT12,E2025S_CREDENTIAL_PROVIDER_CALLBACK(3)
mongoc_auto_encryption_opts_set_kms_providers.3
MONGOC_AUTO_ENCRYPTION_OPTS_SETOKMSlPROVIDERS(3)TION_OPTS_SET_KMS_PROVIDERS(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_kms_providers (
mongoc_auto_encryption_opts_t *opts, const bson_t *kms_providers);
PARAMETERS
+ opts: The mongoc_auto_encryption_opts_t
+ kms_providers: A bson_t containing configuration for an external Key
Management Service (KMS).
kms_providers is a BSON document containing configuration for each KMS
provider.
KMS providers are specified as a string of the form <KMS provider type>
or <KMS provider type>:<KMS provider name>. The supported KMS provider
types are aws, azure, gcp, local, and kmip. The optional name enables
configuring multiple KMS providers with the same KMS provider type
(e.g. aws:name1 and aws:name2 can refer to different AWS accounts). At
least one KMS provider must be specified.
The format for the KMS provider type aws is as follows:
aws: {
accessKeyId: String,
secretAccessKey: String
}
The format for the KMS provider type local is as follows:
local: {
key: <96 byte BSON binary of subtype 0> or String /* The master key used to encrypt/decrypt data keys. May be passed as a base64 encoded string. */
}
The format for the KMS provider type azure is as follows:
azure: {
tenantId: String,
clientId: String,
clientSecret: String,
identityPlatformEndpoint: Optional<String> /* Defaults to login.microsoftonline.com */
}
The format for the KMS provider type gcp is as follows:
gcp: {
email: String,
privateKey: byte[] or String, /* May be passed as a base64 encoded string. */
endpoint: Optional<String> /* Defaults to oauth2.googleapis.com */
}
The format for the KMS provider type kmip is as follows:
kmip: {
endpoint: String
}
KMS providers may include an optional name suffix separate with a
colon. This enables configuring multiple KMS providers with the same
KMS provider type. Example:
"aws:name1": {
accessKeyId: String,
secretAccessKey: String
},
"aws:name2": {
accessKeyId: String,
secretAccessKey: String
}
SEE ALSO:
mongoc_client_enable_auto_encryption()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,O2025RYPTION_OPTS_SET_KMS_PROVIDERS(3)
mongoc_auto_encryption_opts_set_schema_map.3
MONGOC_AUTO_ENCRYPTION_OPTS_SET_SCHEMAmMAP(3)ENCRYPTION_OPTS_SET_SCHEMA_MAP(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_schema_map (mongoc_auto_encryption_opts_t *opts,
const bson_t *schema_map);
PARAMETERS
+ opts: The mongoc_auto_encryption_opts_t
+ schema_map: A bson_t where keys are collection namespaces and values
are JSON schemas.
Supplying a schema map provides more security than relying on JSON
Schemas obtained from the server. It protects against a malicious
server advertising a false JSON Schema, which could trick the client
into sending unencrypted data that should be encrypted.
Schemas supplied in the schema map only apply to configuring automatic
encryption for Client-Side Field Level Encryption. Other validation
rules in the JSON schema will not be enforced by the driver and will
result in an error.
The following is an example of a schema map which configures automatic
encryption for the collection db.coll:
{
"db.coll": {
"properties": {
"encrypted_string": {
"encrypt": {
"keyId": [
{
"$binary": {
"base64": "AAAAAAAAAAAAAAAAAAAAAA==",
"subType": "04"
}
}
],
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
}
}
},
"bsonType": "object"
}
}
The schema map does not apply to collections encrypted with: Queryable
Encryption. Use mongoc_auto_encryption_opts_set_encrypted_fields_map()
instead.
SEE ALSO:
mongoc_client_enable_auto_encryption()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,A2025ENCRYPTION_OPTS_SET_SCHEMA_MAP(3)
mongoc_auto_encryption_opts_set_tls_opts.3
MONGOC_AUTO_ENCRYPTION_OPTS_SET_TLSlOPTS(3)cTO_ENCRYPTION_OPTS_SET_TLS_OPTS(3)
SYNOPSIS
void
mongoc_auto_encryption_opts_set_tls_opts (
mongoc_auto_encryption_opts_t *opts, const bson_t *tls_opts);
PARAMETERS
+ opts: The mongoc_auto_encryption_opts_t
+ tls_opts: A bson_t mapping a Key Management Service (KMS) provider to
a BSON document with TLS options.
tls_opts is a BSON document of the following form:
<KMS provider>: {
tlsCaFile: Optional<String>
tlsCertificateKeyFile: Optional<String>
tlsCertificateKeyFilePassword: Optional<String>
}
The KMS providers aws, azure, gcp, and kmip are supported as keys in
the tls_opts document. They may include an optional name suffix sepa-
rated with a colon. Example: aws:name2.
tls_opts maps the KMS provider name to a BSON document for TLS options.
The BSON document for TLS options may contain the following keys:
+ MONGOC_URI_TLSCERTIFICATEKEYFILE
+ MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD
+ MONGOC_URI_TLSCAFILE
Example use
mongoc_auto_encryption_opts_t *ae_opts = mongoc_auto_encryption_opts_new ();
bson_t *tls_opts = bson_new ();
BCON_APPEND (tls_opts, "kmip", "{", MONGOC_URI_TLSCAFILE, "ca1.pem", "}");
BCON_APPEND (tls_opts, "aws", "{", MONGOC_URI_TLSCAFILE, "ca2.pem", "}");
mongoc_auto_encryption_opts_set_tls_opts (ae_opts, tls_opts);
See Configuring TLS for a description of the behavior of these options.
SEE ALSO:
mongoc_client_enable_auto_encryption()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025O_ENCRYPTION_OPTS_SET_TLS_OPTS(3)
mongoc_auto_encryption_opts_t.3
MONGOC_AUTO_ENCRYPTION_OPTS_T(3) libmongoc MONGOC_AUTO_ENCRYPTION_OPTS_T(3)
Options for enabling automatic encryption and decryption for In-Use Encryp-
tion.
SYNOPSIS
typedef struct _mongoc_auto_encryption_opts_t mongoc_auto_encryption_opts_t;
SEE ALSO:
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_AUTO_ENCRYPTION_OPTS_T(3)
mongoc_bulk_operation_destroy.3
MONGOC_BULK_OPERATION_DESTROY(3) libmongoc MONGOC_BULK_OPERATION_DESTROY(3)
SYNOPSIS
void
mongoc_bulk_operation_destroy (mongoc_bulk_operation_t *bulk);
Destroys a mongoc_bulk_operation_t and frees the structure. Does noth-
ing if bulk is NULL.
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULK_OPERATION_DESTROY(3)
mongoc_bulk_operation_execute.3
MONGOC_BULK_OPERATION_EXECUTE(3) libmongoc MONGOC_BULK_OPERATION_EXECUTE(3)
SYNOPSIS
uint32_t
mongoc_bulk_operation_execute (mongoc_bulk_operation_t *bulk,
bson_t *reply,
bson_error_t *error);
This function executes all operations queued into the bulk operation.
Unless ordered: false was specified in the opts passed to
mongoc_collection_create_bulk_operation_with_opts(), then forward
progress will be stopped upon the first error.
It is only valid to call mongoc_bulk_operation_execute() once on the
same mongoc_bulk_operation_t. Calling repeatedly results in error. Call
mongoc_bulk_operation_destroy() to destroy bulk afterwards.
Changed in version 2.0.0: Calling mongoc_bulk_operation_execute() re-
peatedly results in an error.
WARNING:
reply is always initialized, even upon failure. Callers must call
bson_destroy() to release this potential allocation.
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
ERRORS
Errors are propagated via the error parameter.
RETURNS
On success, returns the server id used. On failure, returns 0 and sets
error.
A write concern timeout or write concern error is considered a failure.
The reply document counts operations and collects error information.
See Bulk Write Operations for examples.
SEE ALSO:
Bulk Write Operations
mongoc_bulk_operation_get_server_id(), which gets the id of the server used even if the operation failed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULK_OPERATION_EXECUTE(3)
mongoc_bulk_operation_get_server_id.3
MONGOC_BULK_OPERATION_GET_SERVER_ID(3)mongocOC_BULK_OPERATION_GET_SERVER_ID(3)
SYNOPSIS
uint32_t
mongoc_bulk_operation_get_server_id (const mongoc_bulk_operation_t *bulk);
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
DESCRIPTION
Retrieves the opaque id of the server used for the operation.
This number is zero until the driver actually uses a server in
mongoc_bulk_operation_execute(). The server id is the same number as
the return value of a successful mongoc_bulk_operation_execute(), so
mongoc_bulk_operation_get_server_id is useful mainly in case
mongoc_bulk_operation_execute() fails and returns zero.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_BULK_OPERATION_GET_SERVER_ID(3)
mongoc_bulk_operation_get_write_concern.3
MONGOC_BULK_OPERATION_GET_WRITE_CONCERN(3)ocULK_OPERATION_GET_WRITE_CONCERN(3)
SYNOPSIS
const mongoc_write_concern_t *
mongoc_bulk_operation_get_write_concern (const mongoc_bulk_operation_t *bulk);
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
DESCRIPTION
Fetches the write concern to be used for bulk.
RETURNS
A mongoc_write_concern_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025LK_OPERATION_GET_WRITE_CONCERN(3)
mongoc_bulk_operation_insert.3
MONGOC_BULK_OPERATION_INSERT(3) libmongoc MONGOC_BULK_OPERATION_INSERT(3)
SYNOPSIS
void
mongoc_bulk_operation_insert (mongoc_bulk_operation_t *bulk,
const bson_t *document);
Queue an insert of a single document into a bulk operation. The insert
is not performed until mongoc_bulk_operation_execute() is called.
This function is superseded by
mongoc_bulk_operation_insert_with_opts().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ document: A bson_t.
ERRORS
Errors are propagated via mongoc_bulk_operation_execute().
SEE ALSO:
Bulk Write Operations
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULK_OPERATION_INSERT(3)
mongoc_bulk_operation_insert_with_opts.3
MONGOC_BULK_OPERATION_INSERT_WITH_OPTS(3)gocBULK_OPERATION_INSERT_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_bulk_operation_insert_with_opts (mongoc_bulk_operation_t *bulk,
const bson_t *document,
const bson_t *opts,
bson_error_t *error); /* OUT */
Queue an insert of a single document into a bulk operation. The insert
is not performed until mongoc_bulk_operation_execute() is called.
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ document: A bson_t.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
ERRORS
Operation errors are propagated via mongoc_bulk_operation_execute(),
while argument validation errors are reported by the error argument.
RETURNS
Returns true on success, and false if passed invalid arguments.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025ULK_OPERATION_INSERT_WITH_OPTS(3)
mongoc_bulk_operation_remove.3
MONGOC_BULK_OPERATION_REMOVE(3) libmongoc MONGOC_BULK_OPERATION_REMOVE(3)
SYNOPSIS
void
mongoc_bulk_operation_remove (mongoc_bulk_operation_t *bulk,
const bson_t *selector);
Remove documents as part of a bulk operation. This only queues the op-
eration. To execute it, call mongoc_bulk_operation_execute().
This function is superseded by
mongoc_bulk_operation_remove_one_with_opts() and
mongoc_bulk_operation_remove_many_with_opts().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t.
ERRORS
Errors are propagated via mongoc_bulk_operation_execute().
SEE ALSO:
mongoc_bulk_operation_remove_one()
mongoc_bulk_operation_remove_one_with_opts()
mongoc_bulk_operation_remove_many_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULK_OPERATION_REMOVE(3)
mongoc_bulk_operation_remove_many_with_opts.3
MONGOC_BULK_OPERATION_REMOVE_MANYOWITHmOPTS(3)ERATION_REMOVE_MANY_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_bulk_operation_remove_many_with_opts (mongoc_bulk_operation_t *bulk,
const bson_t *selector,
const bson_t *opts,
bson_error_t *error); /* OUT */
Delete documents as part of a bulk operation. This only queues the op-
eration. To execute it, call mongoc_bulk_operation_execute().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t that selects which document to remove.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
ERRORS
Operation errors are propagated via mongoc_bulk_operation_execute(),
while argument validation errors are reported by the error argument.
RETURNS
Returns true on success, and false if passed invalid arguments.
SEE ALSO:
mongoc_bulk_operation_remove()
mongoc_bulk_operation_remove_one_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,U2025PERATION_REMOVE_MANY_WITH_OPTS(3)
mongoc_bulk_operation_remove_one.3
MONGOC_BULK_OPERATION_REMOVE_ONE(3)libmongocONGOC_BULK_OPERATION_REMOVE_ONE(3)
SYNOPSIS
void
mongoc_bulk_operation_remove_one (mongoc_bulk_operation_t *bulk,
const bson_t *selector);
Remove a single document as part of a bulk operation. This only queues
the operation. To execute it, call mongoc_bulk_operation_execute().
This function is superseded by
mongoc_bulk_operation_remove_one_with_opts().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t that selects which document to remove.
ERRORS
Errors are propagated via mongoc_bulk_operation_execute().
SEE ALSO:
mongoc_bulk_operation_remove_one_with_opts()
mongoc_bulk_operation_remove_many_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_BULK_OPERATION_REMOVE_ONE(3)
mongoc_bulk_operation_remove_one_with_opts.3
MONGOC_BULK_OPERATION_REMOVE_ONE_WITHbOPTS(3)OPERATION_REMOVE_ONE_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_bulk_operation_remove_one_with_opts (mongoc_bulk_operation_t *bulk,
const bson_t *selector,
const bson_t *opts,
bson_error_t *error); /* OUT */
Remove a single document as part of a bulk operation. This only queues
the operation. To execute it, call mongoc_bulk_operation_execute().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t that selects which document to remove.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
ERRORS
Operation errors are propagated via mongoc_bulk_operation_execute(),
while argument validation errors are reported by the error argument.
RETURNS
Returns true on success, and false if passed invalid arguments.
SEE ALSO:
mongoc_bulk_operation_remove_one()
mongoc_bulk_operation_remove_many_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,B2025OPERATION_REMOVE_ONE_WITH_OPTS(3)
mongoc_bulk_operation_replace_one.3
MONGOC_BULK_OPERATION_REPLACE_ONE(3)ibmongocNGOC_BULK_OPERATION_REPLACE_ONE(3)
SYNOPSIS
void
mongoc_bulk_operation_replace_one (mongoc_bulk_operation_t *bulk,
const bson_t *selector,
const bson_t *document,
bool upsert);
Replace a single document as part of a bulk operation. This only queues
the operation. To execute it, call mongoc_bulk_operation_execute().
This function is superseded by
mongoc_bulk_operation_replace_one_with_opts().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t that selects which document to remove.
+ document: A bson_t containing the replacement document.
+ upsert: true if this should be an upsert.
WARNING:
document may not contain fields with keys containing . or $.
ERRORS
Errors are propagated via mongoc_bulk_operation_execute().
SEE ALSO:
mongoc_bulk_operation_replace_one_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULK_OPERATION_REPLACE_ONE(3)
mongoc_bulk_operation_replace_one_with_opts.3
MONGOC_BULK_OPERATION_REPLACE_ONEOWITHmOPTS(3)ERATION_REPLACE_ONE_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_bulk_operation_replace_one_with_opts (mongoc_bulk_operation_t *bulk,
const bson_t *selector,
const bson_t *document,
const bson_t *opts,
bson_error_t *error); /* OUT */
Replace a single document as part of a bulk operation. This only queues
the operation. To execute it, call mongoc_bulk_operation_execute().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t that selects which document to remove.
+ document: A bson_t containing the replacement document.
+ error: A bson_error_t any errors that may have occurred.
opts may be NULL or a BSON document with additional command options:
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
+ upsert: If true, insert a document if none match selector.
+ sort: Specify a sort order when matching documents.
WARNING:
document may not contain fields with keys containing . or $.
ERRORS
Operation errors are propagated via mongoc_bulk_operation_execute(),
while argument validation errors are reported by the error argument.
RETURNS
Returns true on success, and false if passed invalid arguments.
SEE ALSO:
mongoc_bulk_operation_remove_many_with_opts()
mongoc_bulk_operation_insert()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,U2025PERATION_REPLACE_ONE_WITH_OPTS(3)
mongoc_bulk_operation_set_bypass_document_validation.3
MONGOC_BULK_OPERATION_SETNBYPASSLDOCUMENTgVALIDATION(3)_DOCUMENT_VALIDATION(3)
SYNOPSIS
void
mongoc_bulk_operation_set_bypass_document_validation (
mongoc_bulk_operation_t *bulk, bool bypass);
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ bypass: A boolean.
DESCRIPTION
Will bypass document validation for all operations part of this bulk.
SEE ALSO:
Bulk Operation Bypassing Document Validation
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_BULMayP12,T2025SET_BYPASS_DOCUMENT_VALIDATION(3)
mongoc_bulk_operation_set_client_session.3
MONGOC_BULK_OPERATION_SET_CLIENT_SESSION(3)cLK_OPERATION_SET_CLIENT_SESSION(3)
SYNOPSIS
void
mongoc_bulk_operation_set_client_session (
mongoc_bulk_operation_t *bulk,
mongoc_client_session_t *client_session);
Sets an explicit client session to use for the bulk operation.
It is an error to use a session for unacknowledged writes.
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ client_session: A mongoc_client_session_t. Must be derived from the
same mongoc_client_t as bulk.
SEE ALSO:
mongoc_client_start_session()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025K_OPERATION_SET_CLIENT_SESSION(3)
mongoc_bulk_operation_set_comment.3
MONGOC_BULK_OPERATION_SET_COMMENT(3)ibmongocNGOC_BULK_OPERATION_SET_COMMENT(3)
SYNOPSIS
void
mongoc_bulk_operation_set_comment (
mongoc_bulk_operation_t *bulk, const bson_value_t *comment);
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ comment: A bson_value_t specifying the comment to associate with this
bulk write.
DESCRIPTION
Assigns a comment to attach to all commands executed as part of this
bulk. The comment will appear in log messages, profiler output, and
currentOp output. Comments for write commands are only supported by
MongoDB 4.4+.
It is prohibited to call this function after adding operations to the
bulk.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULK_OPERATION_SET_COMMENT(3)
mongoc_bulk_operation_set_let.3
MONGOC_BULK_OPERATION_SET_LET(3) libmongoc MONGOC_BULK_OPERATION_SET_LET(3)
SYNOPSIS
void
mongoc_bulk_operation_set_let (
mongoc_bulk_operation_t *bulk, const bson_t *let);
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
DESCRIPTION
Defines constants that can be accessed by all update, replace, and
delete operations executed as part of this bulk.
It is prohibited to call this function after adding operations to the
bulk.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULK_OPERATION_SET_LET(3)
mongoc_bulk_operation_set_server_id.3
MONGOC_BULK_OPERATION_SET_SERVER_ID(3)mongocOC_BULK_OPERATION_SET_SERVER_ID(3)
SYNOPSIS
void
mongoc_bulk_operation_set_server_id (mongoc_bulk_operation_t *bulk, uint32_t server_id);
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ server_id: An opaque id identifying the server to use.
DESCRIPTION
Specifies which server to use for the operation. This function has an
effect only if called before mongoc_bulk_operation_execute().
Use mongoc_bulk_operation_set_server_id only for building a language
driver that wraps the C Driver. When writing applications in C, leave
the server id unset and allow the driver to choose a suitable server
for the bulk operation.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_BULK_OPERATION_SET_SERVER_ID(3)
mongoc_bulk_operation_t.3
MONGOC_BULK_OPERATION_T(3) libmongoc MONGOC_BULK_OPERATION_T(3)
Bulk Write Operations
SYNOPSIS
typedef struct _mongoc_bulk_operation_t mongoc_bulk_operation_t;
DESCRIPTION
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 exe-
cute 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_bulkwrite_t
NOTE:
If using MongoDB server 8.0+, prefer mongoc_bulkwrite_t over
mongoc_bulk_operation_t to reduce network round trips.
mongoc_bulkwrite_t uses the bulkWrite server command introduced in
MongoDB server 8.0. bulkWrite command supports insert, update, and
delete operations in the same payload. bulkWrite supports use of
multiple collection namespaces in the same payload.
mongoc_bulk_operation_t uses the insert, update and delete server
commands available in all current MongoDB server versions. Write op-
erations are grouped by type (insert, update, delete) and sent in
separate commands. Only one collection may be specified per bulk
write.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULK_OPERATION_T(3)
mongoc_bulk_operation_update.3
MONGOC_BULK_OPERATION_UPDATE(3) libmongoc MONGOC_BULK_OPERATION_UPDATE(3)
SYNOPSIS
void
mongoc_bulk_operation_update (mongoc_bulk_operation_t *bulk,
const bson_t *selector,
const bson_t *document,
bool upsert);
This function queues an update as part of a bulk operation. This does
not execute the operation. To execute the entirety of the bulk opera-
tion call mongoc_bulk_operation_execute().
document MUST only contain fields whose key starts with $. See the up-
date document specification for more details.
This function is superseded by
mongoc_bulk_operation_update_one_with_opts() and
mongoc_bulk_operation_update_many_with_opts().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t that selects which documents to remove.
+ document: A bson_t containing the update document.
+ upsert: true if an upsert should be performed.
ERRORS
Errors are propagated via mongoc_bulk_operation_execute().
SEE ALSO:
mongoc_bulk_operation_update_one_with_opts()
mongoc_bulk_operation_update_many_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULK_OPERATION_UPDATE(3)
mongoc_bulk_operation_update_many_with_opts.3
MONGOC_BULK_OPERATION_UPDATE_MANYOWITHmOPTS(3)ERATION_UPDATE_MANY_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_bulk_operation_update_many_with_opts (mongoc_bulk_operation_t *bulk,
const bson_t *selector,
const bson_t *document,
const bson_t *opts,
bson_error_t *error); /* OUT */
This function queues an update as part of a bulk operation. This does
not execute the operation. To execute the entirety of the bulk opera-
tion call mongoc_bulk_operation_execute().
WARNING:
document MUST only contain fields whose key starts with $. See the
update document specification for more details.
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t that selects which documents to remove.
+ document: A bson_t containing the update document.
+ error: A bson_error_t any errors that may have occurred.
opts may be NULL or a BSON document with additional command options:
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
+ upsert: If true, insert a document if none match selector.
+ arrayFilters: An array of filters specifying to which array elements
an update should apply.
ERRORS
Operation errors are propagated via mongoc_bulk_operation_execute(),
while argument validation errors are reported by the error argument.
RETURNS
Returns true on success, and false if there is a server or network er-
ror or if passed invalid arguments.
SEE ALSO:
mongoc_bulk_operation_update_one_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,U2025PERATION_UPDATE_MANY_WITH_OPTS(3)
mongoc_bulk_operation_update_one.3
MONGOC_BULK_OPERATION_UPDATE_ONE(3)libmongocONGOC_BULK_OPERATION_UPDATE_ONE(3)
SYNOPSIS
void
mongoc_bulk_operation_update_one (mongoc_bulk_operation_t *bulk,
const bson_t *selector,
const bson_t *document,
bool upsert);
This function queues an update as part of a bulk operation. It will
only modify a single document on the MongoDB server. This function does
not execute the operation. To execute the entirety of the bulk opera-
tion call mongoc_bulk_operation_execute().
This function is superseded by
mongoc_bulk_operation_update_one_with_opts().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t that selects which document to remove.
+ document: A bson_t containing the update document.
+ upsert: true if an upsert should be performed.
WARNING:
document must only contain fields whose key starts with $. See the
update document specification for more details.
SEE ALSO:
mongoc_bulk_operation_update()
mongoc_bulk_operation_update_one_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_BULK_OPERATION_UPDATE_ONE(3)
mongoc_bulk_operation_update_one_with_opts.3
MONGOC_BULK_OPERATION_UPDATE_ONE_WITHbOPTS(3)OPERATION_UPDATE_ONE_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_bulk_operation_update_one_with_opts (mongoc_bulk_operation_t *bulk,
const bson_t *selector,
const bson_t *document,
const bson_t *opts,
bson_error_t *error); /* OUT */
This function queues an update as part of a bulk operation. It will
only modify a single document on the MongoDB server. This function does
not execute the operation. To execute the entirety of the bulk opera-
tion call mongoc_bulk_operation_execute().
PARAMETERS
+ bulk: A mongoc_bulk_operation_t.
+ selector: A bson_t that selects which document to remove.
+ document: A bson_t containing the update document.
+ error: A bson_error_t any errors that may have occurred.
opts may be NULL or a BSON document with additional command options:
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
+ upsert: If true, insert a document if none match selector.
+ sort: Specify a sort order when matching documents.
+ arrayFilters: An array of filters specifying to which array elements
an update should apply.
WARNING:
document must only contain fields whose key starts with $. See the
update document specification for more details.
ERRORS
Operation errors are propagated via mongoc_bulk_operation_execute(),
while argument validation errors are reported by the error argument.
RETURNS
Returns true on success, and false if there is a server or network er-
ror or if passed invalid arguments.
SEE ALSO:
mongoc_bulk_operation_update_many_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,B2025OPERATION_UPDATE_ONE_WITH_OPTS(3)
mongoc_bulkwrite_append_deletemany.3
MONGOC_BULKWRITE_APPEND_DELETEMANY(3)bmongocGOC_BULKWRITE_APPEND_DELETEMANY(3)
SYNOPSIS
bool
mongoc_bulkwrite_append_deletemany (mongoc_bulkwrite_t *self,
const char *ns,
const bson_t *filter,
const mongoc_bulkwrite_deletemanyopts_t *opts /* May be NULL */,
bson_error_t *error);
DESCRIPTION
Adds a multi-document delete into the namespace ns. Returns true on
success. Returns false and sets error if an error occured.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_BULKWRITE_APPEND_DELETEMANY(3)
mongoc_bulkwrite_append_deleteone.3
MONGOC_BULKWRITE_APPEND_DELETEONE(3)ibmongocNGOC_BULKWRITE_APPEND_DELETEONE(3)
SYNOPSIS
bool
mongoc_bulkwrite_append_deleteone (mongoc_bulkwrite_t *self,
const char *ns,
const bson_t *filter,
const mongoc_bulkwrite_deleteoneopts_t *opts /* May be NULL */,
bson_error_t *error);
DESCRIPTION
Adds a single-document delete into the namespace ns. Returns true on
success. Returns false and sets error if an error occured.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULKWRITE_APPEND_DELETEONE(3)
mongoc_bulkwrite_append_insertone.3
MONGOC_BULKWRITE_APPEND_INSERTONE(3)ibmongocNGOC_BULKWRITE_APPEND_INSERTONE(3)
SYNOPSIS
bool
mongoc_bulkwrite_append_insertone (mongoc_bulkwrite_t *self,
const char *ns,
const bson_t *document,
const mongoc_bulkwrite_insertoneopts_t *opts /* May be NULL */,
bson_error_t *error);
DESCRIPTION
Adds a document to insert into the namespace ns. Returns true on suc-
cess. Returns false and sets error if an error occured.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULKWRITE_APPEND_INSERTONE(3)
mongoc_bulkwrite_append_replaceone.3
MONGOC_BULKWRITE_APPEND_REPLACEONE(3)bmongocGOC_BULKWRITE_APPEND_REPLACEONE(3)
SYNOPSIS
bool
mongoc_bulkwrite_append_replaceone (mongoc_bulkwrite_t *self,
const char *ns,
const bson_t *filter,
const bson_t *replacement,
const mongoc_bulkwrite_replaceoneopts_t *opts /* May be NULL */,
bson_error_t *error);
DESCRIPTION
Adds a replace operation for the namespace ns. Returns true on success.
Returns false and sets error if an error occured.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_BULKWRITE_APPEND_REPLACEONE(3)
mongoc_bulkwrite_append_updatemany.3
MONGOC_BULKWRITE_APPEND_UPDATEMANY(3)bmongocGOC_BULKWRITE_APPEND_UPDATEMANY(3)
SYNOPSIS
bool
mongoc_bulkwrite_append_updatemany (mongoc_bulkwrite_t *self,
const char *ns,
const bson_t *filter,
const bson_t *update,
const mongoc_bulkwrite_updatemanyopts_t *opts /* May be NULL */,
bson_error_t *error);
DESCRIPTION
Adds a multi-document update for the namespace ns. Returns true on suc-
cess. Returns false and sets error if an error occured.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_BULKWRITE_APPEND_UPDATEMANY(3)
mongoc_bulkwrite_append_updateone.3
MONGOC_BULKWRITE_APPEND_UPDATEONE(3)ibmongocNGOC_BULKWRITE_APPEND_UPDATEONE(3)
SYNOPSIS
bool
mongoc_bulkwrite_append_updateone (mongoc_bulkwrite_t *self,
const char *ns,
const bson_t *filter,
const bson_t *update,
const mongoc_bulkwrite_updateoneopts_t *opts /* May be NULL */,
bson_error_t *error);
DESCRIPTION
Adds a single-document update for the namespace ns. Returns true on
success. Returns false and sets error if an error occured.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULKWRITE_APPEND_UPDATEONE(3)
mongoc_bulkwrite_deletemanyopts_destroy.3
MONGOC_BULKWRITE_DELETEMANYOPTS_DESTROY(3)ocULKWRITE_DELETEMANYOPTS_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwrite_deletemanyopts_destroy (mongoc_bulkwrite_deletemanyopts_t *self);
DESCRIPTION
Frees a mongoc_bulkwrite_deletemanyopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025LKWRITE_DELETEMANYOPTS_DESTROY(3)
mongoc_bulkwrite_deletemanyopts_new.3
MONGOC_BULKWRITE_DELETEMANYOPTS_NEW(3)mongocOC_BULKWRITE_DELETEMANYOPTS_NEW(3)
SYNOPSIS
mongoc_bulkwrite_deletemanyopts_t *
mongoc_bulkwrite_deletemanyopts_new (void);
DESCRIPTION
Returns a new mongoc_bulkwrite_deletemanyopts_new().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_BULKWRITE_DELETEMANYOPTS_NEW(3)
mongoc_bulkwrite_deletemanyopts_set_collation.3
MONGOC_BULKWRITE_DELETEMANYOPTSOSETlCOLLATION(3)ELETEMANYOPTS_SET_COLLATION(3)
SYNOPSIS
void
mongoc_bulkwrite_deletemanyopts_set_collation (mongoc_bulkwrite_deletemanyopts_t *self, const bson_t *collation);
DESCRIPTION
Specifies a collation.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,K2025E_DELETEMANYOPTS_SET_COLLATION(3)
mongoc_bulkwrite_deletemanyopts_set_hint.3
MONGOC_BULKWRITE_DELETEMANYOPTS_SETlHINT(3)cLKWRITE_DELETEMANYOPTS_SET_HINT(3)
SYNOPSIS
void
mongoc_bulkwrite_deletemanyopts_set_hint (mongoc_bulkwrite_deletemanyopts_t *self, const bson_value_t *hint);
DESCRIPTION
Specifies the index to use. Specify either the index name as a string
or the index key pattern. If specified, then the query system will only
consider plans using the hinted index.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025KWRITE_DELETEMANYOPTS_SET_HINT(3)
mongoc_bulkwrite_deletemanyopts_t.3
MONGOC_BULKWRITE_DELETEMANYOPTS_T(3)ibmongocNGOC_BULKWRITE_DELETEMANYOPTS_T(3)
SYNOPSIS
typedef struct _mongoc_bulkwrite_deletemanyopts_t mongoc_bulkwrite_deletemanyopts_t;
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULKWRITE_DELETEMANYOPTS_T(3)
mongoc_bulkwrite_deleteoneopts_destroy.3
MONGOC_BULKWRITE_DELETEONEOPTS_DESTROY(3)gocBULKWRITE_DELETEONEOPTS_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwrite_deleteoneopts_destroy (mongoc_bulkwrite_deleteoneopts_t *self);
DESCRIPTION
Frees a mongoc_bulkwrite_deleteoneopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025ULKWRITE_DELETEONEOPTS_DESTROY(3)
mongoc_bulkwrite_deleteoneopts_new.3
MONGOC_BULKWRITE_DELETEONEOPTS_NEW(3)bmongocGOC_BULKWRITE_DELETEONEOPTS_NEW(3)
SYNOPSIS
mongoc_bulkwrite_deleteoneopts_t *
mongoc_bulkwrite_deleteoneopts_new (void);
DESCRIPTION
Returns a new mongoc_bulkwrite_deleteoneopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_BULKWRITE_DELETEONEOPTS_NEW(3)
mongoc_bulkwrite_deleteoneopts_set_collation.3
MONGOC_BULKWRITE_DELETEONEOPTS_SETGCOLLATION(3)_DELETEONEOPTS_SET_COLLATION(3)
SYNOPSIS
void
mongoc_bulkwrite_deleteoneopts_set_collation (mongoc_bulkwrite_deleteoneopts_t *self, const bson_t *collation);
DESCRIPTION
Specifies a collation.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,L2025TE_DELETEONEOPTS_SET_COLLATION(3)
mongoc_bulkwrite_deleteoneopts_set_hint.3
MONGOC_BULKWRITE_DELETEONEOPTS_SET_HINT(3)ocULKWRITE_DELETEONEOPTS_SET_HINT(3)
SYNOPSIS
void
mongoc_bulkwrite_deleteoneopts_set_hint (mongoc_bulkwrite_deleteoneopts_t *self, const bson_value_t *hint);
DESCRIPTION
Specifies the index to use. Specify either the index name as a string
or the index key pattern. If specified, then the query system will only
consider plans using the hinted index.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025LKWRITE_DELETEONEOPTS_SET_HINT(3)
mongoc_bulkwrite_deleteoneopts_t.3
MONGOC_BULKWRITE_DELETEONEOPTS_T(3)libmongocONGOC_BULKWRITE_DELETEONEOPTS_T(3)
SYNOPSIS
typedef struct _mongoc_bulkwrite_deleteoneopts_t mongoc_bulkwrite_deleteoneopts_t;
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_BULKWRITE_DELETEONEOPTS_T(3)
mongoc_bulkwrite_destroy.3
MONGOC_BULKWRITE_DESTROY(3) libmongoc MONGOC_BULKWRITE_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwrite_destroy (mongoc_bulkwrite_t *self);
DESCRIPTION
Frees a mongoc_bulkwrite_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITE_DESTROY(3)
mongoc_bulkwrite_execute.3
MONGOC_BULKWRITE_EXECUTE(3) libmongoc MONGOC_BULKWRITE_EXECUTE(3)
SYNOPSIS
mongoc_bulkwritereturn_t
mongoc_bulkwrite_execute (mongoc_bulkwrite_t *self, const mongoc_bulkwriteopts_t *opts);
DESCRIPTION
Executes a mongoc_bulkwrite_t. Once executed, it is an error to call
other functions on self, aside from mongoc_bulkwrite_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITE_EXECUTE(3)
mongoc_bulkwrite_insertoneopts_destroy.3
MONGOC_BULKWRITE_INSERTONEOPTS_DESTROY(3)gocBULKWRITE_INSERTONEOPTS_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwrite_insertoneopts_destroy (mongoc_bulkwrite_insertoneopts_t *self);
DESCRIPTION
Frees a mongoc_bulkwrite_insertoneopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025ULKWRITE_INSERTONEOPTS_DESTROY(3)
mongoc_bulkwrite_insertoneopts_new.3
MONGOC_BULKWRITE_INSERTONEOPTS_NEW(3)bmongocGOC_BULKWRITE_INSERTONEOPTS_NEW(3)
SYNOPSIS
mongoc_bulkwrite_insertoneopts_t *
mongoc_bulkwrite_insertoneopts_new (void);
DESCRIPTION
Returns a new mongoc_bulkwrite_insertoneopts_t. Free with
mongoc_bulkwrite_insertoneopts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_BULKWRITE_INSERTONEOPTS_NEW(3)
mongoc_bulkwrite_insertoneopts_t.3
MONGOC_BULKWRITE_INSERTONEOPTS_T(3)libmongocONGOC_BULKWRITE_INSERTONEOPTS_T(3)
SYNOPSIS
typedef struct _mongoc_bulkwrite_insertoneopts_t mongoc_bulkwrite_insertoneopts_t;
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_BULKWRITE_INSERTONEOPTS_T(3)
mongoc_bulkwrite_new.3
MONGOC_BULKWRITE_NEW(3) libmongoc MONGOC_BULKWRITE_NEW(3)
SYNOPSIS
mongoc_bulkwrite_t *
mongoc_bulkwrite_new (void);
DESCRIPTION
Returns a new mongoc_bulkwrite_t. Free with mongoc_bulkwrite_destroy().
A client must be assigned with mongoc_bulkwrite_set_client() prior to
execution.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITE_NEW(3)
mongoc_bulkwrite_replaceoneopts_destroy.3
MONGOC_BULKWRITE_REPLACEONEOPTS_DESTROY(3)ocULKWRITE_REPLACEONEOPTS_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwrite_replaceoneopts_destroy (mongoc_bulkwrite_replaceoneopts_t *self);
DESCRIPTION
Frees a mongoc_bulkwrite_replaceoneopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025LKWRITE_REPLACEONEOPTS_DESTROY(3)
mongoc_bulkwrite_replaceoneopts_new.3
MONGOC_BULKWRITE_REPLACEONEOPTS_NEW(3)mongocOC_BULKWRITE_REPLACEONEOPTS_NEW(3)
SYNOPSIS
mongoc_bulkwrite_replaceoneopts_t *
mongoc_bulkwrite_replaceoneopts_new (void);
DESCRIPTION
Returns a new mongoc_bulkwrite_replaceoneopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_BULKWRITE_REPLACEONEOPTS_NEW(3)
mongoc_bulkwrite_replaceoneopts_set_collation.3
MONGOC_BULKWRITE_REPLACEONEOPTSOSETlCOLLATION(3)EPLACEONEOPTS_SET_COLLATION(3)
SYNOPSIS
void
mongoc_bulkwrite_replaceoneopts_set_collation (mongoc_bulkwrite_replaceoneopts_t *self, const bson_t *collation);
DESCRIPTION
Specifies a collation.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,K2025E_REPLACEONEOPTS_SET_COLLATION(3)
mongoc_bulkwrite_replaceoneopts_set_hint.3
MONGOC_BULKWRITE_REPLACEONEOPTS_SETlHINT(3)cLKWRITE_REPLACEONEOPTS_SET_HINT(3)
SYNOPSIS
void
mongoc_bulkwrite_replaceoneopts_set_hint (mongoc_bulkwrite_replaceoneopts_t *self, const bson_value_t *hint);
DESCRIPTION
Specifies the index to use. Specify either the index name as a string
or the index key pattern. If specified, then the query system will only
consider plans using the hinted index.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025KWRITE_REPLACEONEOPTS_SET_HINT(3)
mongoc_bulkwrite_replaceoneopts_set_sort.3
MONGOC_BULKWRITE_REPLACEONEOPTS_SETlSORT(3)cLKWRITE_REPLACEONEOPTS_SET_SORT(3)
SYNOPSIS
void
mongoc_bulkwrite_replaceoneopts_set_sort (mongoc_bulkwrite_replaceoneopts_t *self, bson_t* sort);
DESCRIPTION
sort specifies a sorting order if the query matches multiple documents.
The first document matched by the sort order will be replaced. This
option is only sent if the caller explicitly provides a value.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025KWRITE_REPLACEONEOPTS_SET_SORT(3)
mongoc_bulkwrite_replaceoneopts_set_upsert.3
MONGOC_BULKWRITE_REPLACEONEOPTS_SETlUPSERT(3)RITE_REPLACEONEOPTS_SET_UPSERT(3)
SYNOPSIS
void
mongoc_bulkwrite_replaceoneopts_set_upsert (mongoc_bulkwrite_replaceoneopts_t *self, bool upsert);
DESCRIPTION
If upsert is true, creates a new document if no document matches the
query.
The upsert option is not sent if this function is not called. The
server's default value is false.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,B2025RITE_REPLACEONEOPTS_SET_UPSERT(3)
mongoc_bulkwrite_replaceoneopts_t.3
MONGOC_BULKWRITE_REPLACEONEOPTS_T(3)ibmongocNGOC_BULKWRITE_REPLACEONEOPTS_T(3)
SYNOPSIS
typedef struct _mongoc_bulkwrite_replaceoneopts_t mongoc_bulkwrite_replaceoneopts_t;
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULKWRITE_REPLACEONEOPTS_T(3)
mongoc_bulkwrite_set_client.3
MONGOC_BULKWRITE_SET_CLIENT(3) libmongoc MONGOC_BULKWRITE_SET_CLIENT(3)
SYNOPSIS
void
mongoc_bulkwrite_set_client (mongoc_bulkwrite_t *self, mongoc_client_t *client);
DESCRIPTION
Sets the client that will be used to execute the mongoc_bulkwrite_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITE_SET_CLIENT(3)
mongoc_bulkwrite_set_session.3
MONGOC_BULKWRITE_SET_SESSION(3) libmongoc MONGOC_BULKWRITE_SET_SESSION(3)
SYNOPSIS
void
mongoc_bulkwrite_set_session (mongoc_bulkwrite_t *self, mongoc_client_session_t *session);
DESCRIPTION
Sets an explicit session.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITE_SET_SESSION(3)
mongoc_bulkwrite_t.3
MONGOC_BULKWRITE_T(3) libmongoc MONGOC_BULKWRITE_T(3)
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.
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.
NOTE:
If using MongoDB server 8.0+, prefer mongoc_bulkwrite_t over
mongoc_bulk_operation_t to reduce network round trips.
mongoc_bulkwrite_t uses the bulkWrite server command introduced in
MongoDB server 8.0. bulkWrite command supports insert, update, and
delete operations in the same payload. bulkWrite supports use of
multiple collection namespaces in the same payload.
mongoc_bulk_operation_t uses the insert, update and delete server
commands available in all current MongoDB server versions. Write op-
erations are grouped by type (insert, update, delete) and sent in
separate commands. Only one collection may be specified per bulk
write.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITE_T(3)
mongoc_bulkwrite_updatemanyopts_destroy.3
MONGOC_BULKWRITE_UPDATEMANYOPTS_DESTROY(3)ocULKWRITE_UPDATEMANYOPTS_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwrite_updatemanyopts_destroy (mongoc_bulkwrite_updatemanyopts_t *self);
DESCRIPTION
Frees a mongoc_bulkwrite_updatemanyopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025LKWRITE_UPDATEMANYOPTS_DESTROY(3)
mongoc_bulkwrite_updatemanyopts_new.3
MONGOC_BULKWRITE_UPDATEMANYOPTS_NEW(3)mongocOC_BULKWRITE_UPDATEMANYOPTS_NEW(3)
SYNOPSIS
mongoc_bulkwrite_updatemanyopts_t *
mongoc_bulkwrite_updatemanyopts_new (void);
DESCRIPTION
Returns a new mongoc_bulkwrite_updatemanyopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_BULKWRITE_UPDATEMANYOPTS_NEW(3)
mongoc_bulkwrite_updatemanyopts_set_arrayfilters.3
MONGOC_BULKWRITE_UPDATEMANYOPTSOSETlARRAYFILTERS(3)ANYOPTS_SET_ARRAYFILTERS(3)
SYNOPSIS
void
mongoc_bulkwrite_updatemanyopts_set_arrayfilters (mongoc_bulkwrite_updatemanyopts_t *self, const bson_t *arrayfilters);
DESCRIPTION
Sets a set of filters specifying to which array elements an update
should apply.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOCMayL12,I2025PDATEMANYOPTS_SET_ARRAYFILTERS(3)
mongoc_bulkwrite_updatemanyopts_set_collation.3
MONGOC_BULKWRITE_UPDATEMANYOPTSOSETlCOLLATION(3)PDATEMANYOPTS_SET_COLLATION(3)
SYNOPSIS
void
mongoc_bulkwrite_updatemanyopts_set_collation (mongoc_bulkwrite_updatemanyopts_t *self, const bson_t *collation);
DESCRIPTION
Specifies a collation.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,K2025E_UPDATEMANYOPTS_SET_COLLATION(3)
mongoc_bulkwrite_updatemanyopts_set_hint.3
MONGOC_BULKWRITE_UPDATEMANYOPTS_SETlHINT(3)cLKWRITE_UPDATEMANYOPTS_SET_HINT(3)
SYNOPSIS
void
mongoc_bulkwrite_updatemanyopts_set_hint (mongoc_bulkwrite_updatemanyopts_t *self, const bson_value_t *hint);
DESCRIPTION
Specifies the index to use. Specify either the index name as a string
or the index key pattern. If specified, then the query system will only
consider plans using the hinted index.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025KWRITE_UPDATEMANYOPTS_SET_HINT(3)
mongoc_bulkwrite_updatemanyopts_set_upsert.3
MONGOC_BULKWRITE_UPDATEMANYOPTS_SETlUPSERT(3)RITE_UPDATEMANYOPTS_SET_UPSERT(3)
SYNOPSIS
void
mongoc_bulkwrite_updatemanyopts_set_upsert (mongoc_bulkwrite_updatemanyopts_t *self, bool upsert);
DESCRIPTION
If upsert is true, creates a new document if no document matches the
query.
The upsert option is not sent if this function is not called. The
server's default value is false.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,B2025RITE_UPDATEMANYOPTS_SET_UPSERT(3)
mongoc_bulkwrite_updatemanyopts_t.3
MONGOC_BULKWRITE_UPDATEMANYOPTS_T(3)ibmongocNGOC_BULKWRITE_UPDATEMANYOPTS_T(3)
SYNOPSIS
typedef struct _mongoc_bulkwrite_updatemanyopts_t mongoc_bulkwrite_updatemanyopts_t;
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULKWRITE_UPDATEMANYOPTS_T(3)
mongoc_bulkwrite_updateoneopts_destroy.3
MONGOC_BULKWRITE_UPDATEONEOPTS_DESTROY(3)gocBULKWRITE_UPDATEONEOPTS_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwrite_updateoneopts_destroy (mongoc_bulkwrite_updateoneopts_t *self);
DESCRIPTION
Frees a mongoc_bulkwrite_updateoneopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025ULKWRITE_UPDATEONEOPTS_DESTROY(3)
mongoc_bulkwrite_updateoneopts_new.3
MONGOC_BULKWRITE_UPDATEONEOPTS_NEW(3)bmongocGOC_BULKWRITE_UPDATEONEOPTS_NEW(3)
SYNOPSIS
mongoc_bulkwrite_updateoneopts_t *
mongoc_bulkwrite_updateoneopts_new (void);
DESCRIPTION
Returns a new mongoc_bulkwrite_updateoneopts_t. Free with
mongoc_bulkwrite_updateoneopts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_BULKWRITE_UPDATEONEOPTS_NEW(3)
mongoc_bulkwrite_updateoneopts_set_arrayfilters.3
MONGOC_BULKWRITE_UPDATEONEOPTSNSET_ARRAYFILTERS(3)EONEOPTS_SET_ARRAYFILTERS(3)
SYNOPSIS
void
mongoc_bulkwrite_updateoneopts_set_arrayfilters (mongoc_bulkwrite_updateoneopts_t *self, const bson_t *arrayfilters);
DESCRIPTION
Sets a set of filters specifying to which array elements an update
should apply.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayU12,R2025UPDATEONEOPTS_SET_ARRAYFILTERS(3)
mongoc_bulkwrite_updateoneopts_set_collation.3
MONGOC_BULKWRITE_UPDATEONEOPTS_SETGCOLLATION(3)_UPDATEONEOPTS_SET_COLLATION(3)
SYNOPSIS
void
mongoc_bulkwrite_updateoneopts_set_collation (mongoc_bulkwrite_updateoneopts_t *self, const bson_t *collation);
DESCRIPTION
Specifies a collation.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,L2025TE_UPDATEONEOPTS_SET_COLLATION(3)
mongoc_bulkwrite_updateoneopts_set_hint.3
MONGOC_BULKWRITE_UPDATEONEOPTS_SET_HINT(3)ocULKWRITE_UPDATEONEOPTS_SET_HINT(3)
SYNOPSIS
void
mongoc_bulkwrite_updateoneopts_set_hint (mongoc_bulkwrite_updateoneopts_t *self, const bson_value_t *hint);
DESCRIPTION
Specifies the index to use. Specify either the index name as a string
or the index key pattern. If specified, then the query system will only
consider plans using the hinted index.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025LKWRITE_UPDATEONEOPTS_SET_HINT(3)
mongoc_bulkwrite_updateoneopts_set_sort.3
MONGOC_BULKWRITE_UPDATEONEOPTS_SET_SORT(3)ocULKWRITE_UPDATEONEOPTS_SET_SORT(3)
SYNOPSIS
void
mongoc_bulkwrite_updateoneopts_set_sort (mongoc_bulkwrite_updateoneopts_t *self, bson_t* sort);
DESCRIPTION
sort specifies a sorting order if the query matches multiple documents.
The first document matched by the sort order will be updated. This op-
tion is only sent if the caller explicitly provides a value.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025LKWRITE_UPDATEONEOPTS_SET_SORT(3)
mongoc_bulkwrite_updateoneopts_set_upsert.3
MONGOC_BULKWRITE_UPDATEONEOPTS_SETMUPSERT(3)KWRITE_UPDATEONEOPTS_SET_UPSERT(3)
SYNOPSIS
void
mongoc_bulkwrite_updateoneopts_set_upsert (mongoc_bulkwrite_updateoneopts_t *self, bool upsert);
DESCRIPTION
If upsert is true, creates a new document if no document matches the
query.
The upsert option is not sent if this function is not called. The
server's default value is false.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025WRITE_UPDATEONEOPTS_SET_UPSERT(3)
mongoc_bulkwrite_updateoneopts_t.3
MONGOC_BULKWRITE_UPDATEONEOPTS_T(3)libmongocONGOC_BULKWRITE_UPDATEONEOPTS_T(3)
SYNOPSIS
typedef struct _mongoc_bulkwrite_updateoneopts_t mongoc_bulkwrite_updateoneopts_t;
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_BULKWRITE_UPDATEONEOPTS_T(3)
mongoc_bulkwriteexception_destroy.3
MONGOC_BULKWRITEEXCEPTION_DESTROY(3)ibmongocNGOC_BULKWRITEEXCEPTION_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwriteexception_destroy (mongoc_bulkwriteexception_t *self);
DESCRIPTION
Frees a mongoc_bulkwriteexception_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULKWRITEEXCEPTION_DESTROY(3)
mongoc_bulkwriteexception_error.3
MONGOC_BULKWRITEEXCEPTION_ERROR(3) libmongocMONGOC_BULKWRITEEXCEPTION_ERROR(3)
SYNOPSIS
bool
mongoc_bulkwriteexception_error (const mongoc_bulkwriteexception_t *self, bson_error_t *error);
DESCRIPTION
Returns true and sets error if there was a top-level error. Returns
false if there was no top-level error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_BULKWRITEEXCEPTION_ERROR(3)
mongoc_bulkwriteexception_errorreply.3
MONGOC_BULKWRITEEXCEPTION_ERRORREPLY(3)ongocC_BULKWRITEEXCEPTION_ERRORREPLY(3)
SYNOPSIS
const bson_t *
mongoc_bulkwriteexception_errorreply (const mongoc_bulkwriteexception_t *self);
DESCRIPTION
Returns a possible server reply related to the error, or an empty docu-
ment.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_BULKWRITEEXCEPTION_ERRORREPLY(3)
mongoc_bulkwriteexception_t.3
MONGOC_BULKWRITEEXCEPTION_T(3) libmongoc MONGOC_BULKWRITEEXCEPTION_T(3)
SYNOPSIS
typedef struct _mongoc_bulkwriteexception_t mongoc_bulkwriteexception_t;
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITEEXCEPTION_T(3)
mongoc_bulkwriteexception_writeconcernerrors.3
MONGOC_BULKWRITEEXCEPTION_WRITECONCERNERRORS(3)EXCEPTION_WRITECONCERNERRORS(3)
SYNOPSIS
const bson_t *
mongoc_bulkwriteexception_writeconcernerrors (const mongoc_bulkwriteexception_t *self);
DESCRIPTION
Returns a BSON array of write concern errors. Example:
[
{ "code" : 123, "message" : "foo", "details" : { } },
{ "code" : 456, "message" : "bar", "details" : { } }
]
Returns an empty array if there are no write concern errors.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,L2025TEEXCEPTION_WRITECONCERNERRORS(3)
mongoc_bulkwriteexception_writeerrors.3
MONGOC_BULKWRITEEXCEPTION_WRITEERRORS(3)ngoc_BULKWRITEEXCEPTION_WRITEERRORS(3)
SYNOPSIS
const bson_t *
mongoc_bulkwriteexception_writeerrors (const mongoc_bulkwriteexception_t *self);
DESCRIPTION
Returns a BSON document mapping model indexes to write errors. Example:
{
"0" : { "code" : 123, "message" : "foo", "details" : { } },
"1" : { "code" : 456, "message" : "bar", "details" : { } }
}
Returns an empty document if there are no write errors.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025BULKWRITEEXCEPTION_WRITEERRORS(3)
mongoc_bulkwriteopts_destroy.3
MONGOC_BULKWRITEOPTS_DESTROY(3) libmongoc MONGOC_BULKWRITEOPTS_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwriteopts_destroy (mongoc_bulkwriteopts_t *self);
DESCRIPTION
Frees a mongoc_bulkwriteopts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITEOPTS_DESTROY(3)
mongoc_bulkwriteopts_new.3
MONGOC_BULKWRITEOPTS_NEW(3) libmongoc MONGOC_BULKWRITEOPTS_NEW(3)
SYNOPSIS
mongoc_bulkwriteopts_t *
mongoc_bulkwriteopts_new (void);
DESCRIPTION
Returns a new mongoc_bulkwriteopts_t. Free with
mongoc_bulkwriteopts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITEOPTS_NEW(3)
mongoc_bulkwriteopts_set_bypassdocumentvalidation.3
MONGOC_BULKWRITEOPTS_SET_BYPASSDOCUMENTVALIDATION(3)YPASSDOCUMENTVALIDATION(3)
SYNOPSIS
void
mongoc_bulkwriteopts_set_bypassdocumentvalidation (mongoc_bulkwriteopts_t *self, bool bypassdocumentvalidation);
DESCRIPTION
If bypassdocumentvalidation is true, allows the writes to opt out of
document-level validation.
This option is only sent to the server if
mongoc_bulkwriteopts_set_bypassdocumentvalidation() is called. The
server's default value is false.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_MayK12,T2025S_SET_BYPASSDOCUMENTVALIDATION(3)
mongoc_bulkwriteopts_set_comment.3
MONGOC_BULKWRITEOPTS_SET_COMMENT(3)libmongocONGOC_BULKWRITEOPTS_SET_COMMENT(3)
SYNOPSIS
void
mongoc_bulkwriteopts_set_comment (mongoc_bulkwriteopts_t *self, const bson_value_t *comment);
DESCRIPTION
Enables users to specify an arbitrary comment to help trace the opera-
tion through the database profiler, currentOp and logs.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_BULKWRITEOPTS_SET_COMMENT(3)
mongoc_bulkwriteopts_set_extra.3
MONGOC_BULKWRITEOPTS_SET_EXTRA(3) libmongoc MONGOC_BULKWRITEOPTS_SET_EXTRA(3)
SYNOPSIS
void
mongoc_bulkwriteopts_set_extra (mongoc_bulkwriteopts_t *self, const bson_t *extra);
DESCRIPTION
Appends all fields in extra to the outgoing bulkWrite command. Intended
to support future server options. Prefer other mongoc_bulk-
writeopts_set_* helpers to avoid unexpected option conflicts.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_BULKWRITEOPTS_SET_EXTRA(3)
mongoc_bulkwriteopts_set_let.3
MONGOC_BULKWRITEOPTS_SET_LET(3) libmongoc MONGOC_BULKWRITEOPTS_SET_LET(3)
SYNOPSIS
void
mongoc_bulkwriteopts_set_let (mongoc_bulkwriteopts_t *self, const bson_t *let);
DESCRIPTION
let is a map of parameter names and values to apply to all operations
within the bulk write. Value must be constant or closed expressions
that do not reference document fields. Parameters can then be accessed
as variables in an aggregate expression context (e.g. "$$var").
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITEOPTS_SET_LET(3)
mongoc_bulkwriteopts_set_ordered.3
MONGOC_BULKWRITEOPTS_SET_ORDERED(3)libmongocONGOC_BULKWRITEOPTS_SET_ORDERED(3)
SYNOPSIS
void
mongoc_bulkwriteopts_set_ordered (mongoc_bulkwriteopts_t *self, bool ordered);
DESCRIPTION
ordered specifies whether the operations in this bulk write should be
executed in the order in which they were specified. If false, writes
will continue to be executed if an individual write fails. If true,
writes will stop executing if an individual write fails.
By default, bulk writes are ordered.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_BULKWRITEOPTS_SET_ORDERED(3)
mongoc_bulkwriteopts_set_serverid.3
MONGOC_BULKWRITEOPTS_SET_SERVERID(3)ibmongocNGOC_BULKWRITEOPTS_SET_SERVERID(3)
SYNOPSIS
void
mongoc_bulkwriteopts_set_serverid (mongoc_bulkwriteopts_t *self, uint32_t serverid);
DESCRIPTION
Identifies which server to perform the operation. Intended for use by
wrapping drivers that select a server before running the operation.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_BULKWRITEOPTS_SET_SERVERID(3)
mongoc_bulkwriteopts_set_verboseresults.3
MONGOC_BULKWRITEOPTS_SET_VERBOSERESULTS(3)ocULKWRITEOPTS_SET_VERBOSERESULTS(3)
SYNOPSIS
void
mongoc_bulkwriteopts_set_verboseresults (mongoc_bulkwriteopts_t *self, bool verboseresults);
DESCRIPTION
If verboseresults is true, detailed results for each successful opera-
tion will be included in the returned results.
By default, verbose results are not included.
Verbose results can be obtained with the following:
+ mongoc_bulkwriteresult_insertresults()
+ mongoc_bulkwriteresult_updateresults()
+ mongoc_bulkwriteresult_deleteresults()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025LKWRITEOPTS_SET_VERBOSERESULTS(3)
mongoc_bulkwriteopts_set_writeconcern.3
MONGOC_BULKWRITEOPTS_SET_WRITECONCERN(3)ngoc_BULKWRITEOPTS_SET_WRITECONCERN(3)
SYNOPSIS
void
mongoc_bulkwriteopts_set_writeconcern (mongoc_bulkwriteopts_t *self, const mongoc_write_concern_t *writeconcern);
DESCRIPTION
writeconcern is the write concern to use for this bulk write. If a
write concern is not set, defaults to the write concern set on the
mongoc_client_t passed in mongoc_client_bulkwrite_new().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025BULKWRITEOPTS_SET_WRITECONCERN(3)
mongoc_bulkwriteopts_t.3
MONGOC_BULKWRITEOPTS_T(3) libmongoc MONGOC_BULKWRITEOPTS_T(3)
SYNOPSIS
typedef struct _mongoc_bulkwriteopts_t mongoc_bulkwriteopts_t;
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITEOPTS_T(3)
mongoc_bulkwriteresult_deletedcount.3
MONGOC_BULKWRITERESULT_DELETEDCOUNT(3)mongocOC_BULKWRITERESULT_DELETEDCOUNT(3)
SYNOPSIS
int64_t
mongoc_bulkwriteresult_deletedcount (const mongoc_bulkwriteresult_t *self);
DESCRIPTION
Returns the total number of documents deleted across all delete opera-
tions.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_BULKWRITERESULT_DELETEDCOUNT(3)
mongoc_bulkwriteresult_deleteresults.3
MONGOC_BULKWRITERESULT_DELETERESULTS(3)ongocC_BULKWRITERESULT_DELETERESULTS(3)
SYNOPSIS
const bson_t *
mongoc_bulkwriteresult_deleteresults (const mongoc_bulkwriteresult_t *self);
DESCRIPTION
Returns the results of each individual delete operation that was suc-
cessfully performed. Example:
{
"0" : { "deletedCount" : 1 },
"1" : { "deletedCount" : 2 }
}
Returns NULL if verbose results were not requested. Request verbose re-
sults with mongoc_bulkwriteopts_set_verboseresults().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_BULKWRITERESULT_DELETERESULTS(3)
mongoc_bulkwriteresult_destroy.3
MONGOC_BULKWRITERESULT_DESTROY(3) libmongoc MONGOC_BULKWRITERESULT_DESTROY(3)
SYNOPSIS
void
mongoc_bulkwriteresult_destroy (mongoc_bulkwriteresult_t *self);
DESCRIPTION
Frees a mongoc_bulkwriteresult_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_BULKWRITERESULT_DESTROY(3)
mongoc_bulkwriteresult_insertedcount.3
MONGOC_BULKWRITERESULT_INSERTEDCOUNT(3)ongocC_BULKWRITERESULT_INSERTEDCOUNT(3)
SYNOPSIS
int64_t
mongoc_bulkwriteresult_insertedcount (const mongoc_bulkwriteresult_t *self);
DESCRIPTION
Returns the total number of documents inserted across all insert opera-
tions.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_BULKWRITERESULT_INSERTEDCOUNT(3)
mongoc_bulkwriteresult_insertresults.3
MONGOC_BULKWRITERESULT_INSERTRESULTS(3)ongocC_BULKWRITERESULT_INSERTRESULTS(3)
SYNOPSIS
const bson_t *
mongoc_bulkwriteresult_insertresults (const mongoc_bulkwriteresult_t *self);
DESCRIPTION
Returns the results of each individual insert operation that was suc-
cessfully performed. Example:
{
"0" : { "insertedId" : "foo" },
"1" : { "insertedId" : "bar" }
}
Returns NULL if verbose results were not requested. Request verbose re-
sults with mongoc_bulkwriteopts_set_verboseresults().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_BULKWRITERESULT_INSERTRESULTS(3)
mongoc_bulkwriteresult_matchedcount.3
MONGOC_BULKWRITERESULT_MATCHEDCOUNT(3)mongocOC_BULKWRITERESULT_MATCHEDCOUNT(3)
SYNOPSIS
int64_t
mongoc_bulkwriteresult_matchedcount (const mongoc_bulkwriteresult_t *self);
DESCRIPTION
Returns the total number of documents matched across all update opera-
tions.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_BULKWRITERESULT_MATCHEDCOUNT(3)
mongoc_bulkwriteresult_modifiedcount.3
MONGOC_BULKWRITERESULT_MODIFIEDCOUNT(3)ongocC_BULKWRITERESULT_MODIFIEDCOUNT(3)
SYNOPSIS
int64_t
mongoc_bulkwriteresult_modifiedcount (const mongoc_bulkwriteresult_t *self);
DESCRIPTION
Returns the total number of documents modified across all update opera-
tions.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_BULKWRITERESULT_MODIFIEDCOUNT(3)
mongoc_bulkwriteresult_serverid.3
MONGOC_BULKWRITERESULT_SERVERID(3) libmongocMONGOC_BULKWRITERESULT_SERVERID(3)
SYNOPSIS
uint32_t
mongoc_bulkwriteresult_serverid (const mongoc_bulkwriteresult_t *self);
DESCRIPTION
Returns the most recently selected server. The returned value may dif-
fer from a serverid previously set with
mongoc_bulkwriteopts_set_serverid() if a retry occurred. Intended for
use by wrapping drivers that select a server before running the opera-
tion.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_BULKWRITERESULT_SERVERID(3)
mongoc_bulkwriteresult_t.3
MONGOC_BULKWRITERESULT_T(3) libmongoc MONGOC_BULKWRITERESULT_T(3)
SYNOPSIS
typedef struct _mongoc_bulkwriteresult_t mongoc_bulkwriteresult_t;
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITERESULT_T(3)
mongoc_bulkwriteresult_updateresults.3
MONGOC_BULKWRITERESULT_UPDATERESULTS(3)ongocC_BULKWRITERESULT_UPDATERESULTS(3)
SYNOPSIS
const bson_t *
mongoc_bulkwriteresult_updateresults (const mongoc_bulkwriteresult_t *self);
DESCRIPTION
Returns the results of each individual update operation that was suc-
cessfully performed. Example:
{
"0" : { "matchedCount" : 2, "modifiedCount" : 2 },
"1" : { "matchedCount" : 1, "modifiedCount" : 0, "upsertedId" : "foo" }
}
Returns NULL if verbose results were not requested. Request verbose re-
sults with mongoc_bulkwriteopts_set_verboseresults().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_BULKWRITERESULT_UPDATERESULTS(3)
mongoc_bulkwriteresult_upsertedcount.3
MONGOC_BULKWRITERESULT_UPSERTEDCOUNT(3)ongocC_BULKWRITERESULT_UPSERTEDCOUNT(3)
SYNOPSIS
int64_t
mongoc_bulkwriteresult_upsertedcount (const mongoc_bulkwriteresult_t *self);
DESCRIPTION
Returns the total number of documents upserted across all update opera-
tions.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_BULKWRITERESULT_UPSERTEDCOUNT(3)
mongoc_bulkwritereturn_t.3
MONGOC_BULKWRITERETURN_T(3) libmongoc MONGOC_BULKWRITERETURN_T(3)
SYNOPSIS
typedef struct {
mongoc_bulkwriteresult_t *res; // NULL if no known successful writes or write was unacknowledged.
mongoc_bulkwriteexception_t *exc; // NULL if no error.
} mongoc_bulkwritereturn_t;
DESCRIPTION
mongoc_bulkwritereturn_t is returned by mongoc_bulkwrite_execute().
res or exc may outlive the mongoc_bulkwrite_t that was executed.
res is NULL if the mongoc_bulkwrite_t has no known successful writes or
was executed with an unacknowledged write concern.
res must be freed with mongoc_bulkwriteresult_destroy().
exc is NULL if no error occurred.
exc must be freed with mongoc_bulkwriteexception_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_BULKWRITERETURN_T(3)
mongoc_change_stream_destroy.3
MONGOC_CHANGE_STREAM_DESTROY(3) libmongoc MONGOC_CHANGE_STREAM_DESTROY(3)
SYNOPSIS
void
mongoc_change_stream_destroy (mongoc_change_stream_t *stream);
Destroys a change stream and associated data.
PARAMETERS
+ stream: An allocated mongoc_change_stream_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CHANGE_STREAM_DESTROY(3)
mongoc_change_stream_error_document.3
MONGOC_CHANGE_STREAM_ERROR_DOCUMENT(3)mongocOC_CHANGE_STREAM_ERROR_DOCUMENT(3)
SYNOPSIS
bool
mongoc_change_stream_error_document (mongoc_change_stream_t *stream,
bson_error_t *err,
const bson_t **reply);
Checks if an error has occurred when creating or iterating over a
change stream.
Similar to mongoc_cursor_error_document() if the error has occurred
client-side then the reply will be set to an empty BSON document. If
the error occurred server-side, reply is set to the server's reply doc-
ument.
PARAMETERS
+ stream: A mongoc_change_stream_t.
+ err: An optional location for a bson_error_t or NULL.
+ reply: A location for a bson_t.
RETURNS
A boolean indicating if there was an error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_CHANGE_STREAM_ERROR_DOCUMENT(3)
mongoc_change_stream_get_resume_token.3
MONGOC_CHANGE_STREAM_GET_RESUME_TOKEN(3)ngoc_CHANGE_STREAM_GET_RESUME_TOKEN(3)
SYNOPSIS
const bson_t *
mongoc_change_stream_get_resume_token (mongoc_change_stream_t *stream);
This function returns the cached resume token, which may be passed as
either the resumeAfter or startAfter option of a watch function to
start a new change stream from the same point.
PARAMETERS
+ stream: A mongoc_change_stream_t.
RETURNS
A bson_t that should not be modified or freed.
Returns NULL if no resume token is available. This is possible if the
change stream has not been iterated and neither resumeAfter nor
startAfter options were specified in the watch function.
LIFECYCLE
The returned bson_t is valid for the lifetime of stream and its data
may be updated if mongoc_change_stream_next() is called after this
function. The value may be copied to extend its lifetime or preserve
the current resume token.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025CHANGE_STREAM_GET_RESUME_TOKEN(3)
mongoc_change_stream_next.3
MONGOC_CHANGE_STREAM_NEXT(3) libmongoc MONGOC_CHANGE_STREAM_NEXT(3)
SYNOPSIS
bool
mongoc_change_stream_next (mongoc_change_stream_t *stream,
const bson_t **bson);
This function iterates the underlying cursor, setting bson to the next
document. This will block for a maximum of maxAwaitTimeMS milliseconds
as specified in the options when created, or the default timeout if
omitted. Data may be returned before the timeout. If no data is re-
turned this function returns false.
PARAMETERS
+ stream: A mongoc_change_stream_t.
+ bson: The location for the resulting document.
RETURNS
This function returns true if a valid bson document was read from the
stream. Otherwise, false if there was an error or no document was
available.
Errors can be determined with the mongoc_change_stream_error_document()
function.
LIFECYCLE
Similar to mongoc_cursor_next() the lifetime of bson is until the next
call to mongoc_change_stream_next(), so it needs to be copied to extend
the lifetime.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CHANGE_STREAM_NEXT(3)
mongoc_change_stream_t.3
MONGOC_CHANGE_STREAM_T(3) libmongoc MONGOC_CHANGE_STREAM_T(3)
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 in-
stead of a raw aggregation with a $changeStream stage. For more infor-
mation see the MongoDB Manual Entry on Change Streams.
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: %s\n"
"error message: %s\n",
uri_string,
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.
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.
Additionally, change streams can start returning changes at an opera-
tion 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 exclu-
sive options. Setting more than one will result in a server error.
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: %s\n"
"error message: %s\n",
uri_string,
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;
}
The following example shows using startAtOperationTime to synchronize a
change stream with another operation.
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: %s\n"
"error message: %s\n",
uri_string,
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;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CHANGE_STREAM_T(3)
mongoc_check_version.3
MONGOC_CHECK_VERSION(3) libmongoc MONGOC_CHECK_VERSION(3)
SYNOPSIS
bool
mongoc_check_version (int required_major,
int required_minor,
int required_micro);
PARAMETERS
+ required_major: The minimum major version required.
+ required_minor: The minimum minor version required.
+ required_micro: The minimum micro version required.
RETURNS
True if libmongoc's version is greater than or equal to the required
version.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CHECK_VERSION(3)
mongoc_cleanup.3
MONGOC_CLEANUP(3) libmongoc MONGOC_CLEANUP(3)
SYNOPSIS
void
mongoc_cleanup (void);
DESCRIPTION
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.
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 re-
lease 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().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLEANUP(3)
mongoc_client_bulkwrite_new.3
MONGOC_CLIENT_BULKWRITE_NEW(3) libmongoc MONGOC_CLIENT_BULKWRITE_NEW(3)
SYNOPSIS
mongoc_bulkwrite_t *
mongoc_client_bulkwrite_new (mongoc_client_t *self);
DESCRIPTION
Returns a new mongoc_bulkwrite_t. Free with mongoc_bulkwrite_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_BULKWRITE_NEW(3)
mongoc_client_command_simple.3
MONGOC_CLIENT_COMMAND_SIMPLE(3) libmongoc MONGOC_CLIENT_COMMAND_SIMPLE(3)
SYNOPSIS
bool
mongoc_client_command_simple (mongoc_client_t *client,
const char *db_name,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
bson_t *reply,
bson_error_t *error);
The client's read preference, read concern, and write concern are not
applied to the command.
WARNING:
reply is always set, and should be released with bson_destroy().
This function is not considered a retryable read operation.
PARAMETERS
+ client: A mongoc_client_t.
+ db_name: The name of the database to run the command on.
+ command: A bson_t containing the command specification.
+ read_prefs: An optional mongoc_read_prefs_t. Otherwise, the command
uses mode MONGOC_READ_PRIMARY.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
This function does not check the server response for a write concern
error or write concern timeout.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_COMMAND_SIMPLE(3)
mongoc_client_command_simple_with_server_id.3
MONGOC_CLIENT_COMMAND_SIMPLE_WITHOSERVERnID(3)COMMAND_SIMPLE_WITH_SERVER_ID(3)
SYNOPSIS
bool
mongoc_client_command_simple_with_server_id (
mongoc_client_t *client,
const char *db_name,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
uint32_t server_id,
bson_t *reply,
bson_error_t *error);
This function executes a command on a specific server, using the data-
base and command specification provided.
This function is not considered a retryable read operation.
PARAMETERS
+ client: A mongoc_client_t.
+ db_name: The name of the database to run the command on.
+ read_prefs: An optional mongoc_read_prefs_t.
+ server_id: An opaque id specifying which server to use.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or a NULL.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
This function does not check the server response for a write concern
error or write concern timeout.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,L2025_COMMAND_SIMPLE_WITH_SERVER_ID(3)
mongoc_client_command_with_opts.3
MONGOC_CLIENT_COMMAND_WITH_OPTS(3) libmongocMONGOC_CLIENT_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_client_command_with_opts (
mongoc_client_t *client,
const char *db_name,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, interpreting opts according to the
MongoDB server version. To send a raw command to the server without any
of this logic, use mongoc_client_command_simple().
Read preferences, read and write concern, and collation can be overrid-
den by various sources. The highest-priority sources for these options
are listed first:
+-----------------+--------------+---------------+-----------+
|Read Preferences | Read Concern | Write Concern | Collation |
+-----------------+--------------+---------------+-----------+
|read_prefs | opts | opts | opts |
+-----------------+--------------+---------------+-----------+
|Transaction | Transaction | Transaction | |
+-----------------+--------------+---------------+-----------+
In a transaction, read concern and write concern are prohibited in opts
and the read preference must be primary or NULL. See the example for
transactions and for the "distinct" command with opts.
reply is always initialized, and must be freed with bson_destroy().
This function is not considered a retryable read operation.
PARAMETERS
+ client: A mongoc_client_t.
+ db_name: The name of the database to run the command on.
+ command: A bson_t containing the command specification.
+ read_prefs: An optional mongoc_read_prefs_t.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
client, and use mongoc_client_session_append() to add the session to
opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
The reply is not parsed for a write concern timeout or write concern
error.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_CLIENT_COMMAND_WITH_OPTS(3)
mongoc_client_decryption_decrypt.3
MONGOC_CLIENT_DECRYPTION_DECRYPT(3)libmongocONGOC_CLIENT_DECRYPTION_DECRYPT(3)
SYNOPSIS
bool
mongoc_client_encryption_decrypt (mongoc_client_encryption_t *client_encryption,
const bson_value_t *ciphertext,
bson_value_t *value,
bson_error_t *error);
Performs explicit decryption.
value is always initialized (even on failure). Caller must call
bson_value_destroy() to free.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t
+ ciphertext: The ciphertext (a BSON binary with subtype 6) to decrypt.
+ value: A bson_value_t for the resulting decrypted value.
+ error: A bson_error_t set on failure.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_enable_auto_encryption()
mongoc_client_encryption_encrypt()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_CLIENT_DECRYPTION_DECRYPT(3)
mongoc_client_destroy.3
MONGOC_CLIENT_DESTROY(3) libmongoc MONGOC_CLIENT_DESTROY(3)
SYNOPSIS
void
mongoc_client_destroy (mongoc_client_t *client);
Release all resources associated with client and free the structure.
Does nothing if client is NULL.
Only call mongoc_client_destroy() on a single-threaded client. Do not
call on a mongoc_client_t obtained from a mongoc_client_pool_t, which
should instead be pushed back with mongoc_client_pool_push().
PARAMETERS
+ client: A mongoc_client_t.
SEE ALSO:
mongoc_client_pool_push() to push a multi-threaded client back onto a pool.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_DESTROY(3)
mongoc_client_enable_auto_encryption.3
MONGOC_CLIENT_ENABLE_AUTO_ENCRYPTION(3)ongocC_CLIENT_ENABLE_AUTO_ENCRYPTION(3)
SYNOPSIS
bool
mongoc_client_enable_auto_encryption (mongoc_client_t *client,
mongoc_auto_encryption_opts_t* opts,
bson_error_t* error);
Enable automatic In-Use Encryption on a mongoc_client_t. Requires lib-
mongoc to be built with support for In-Use Encryption. See In-Use En-
cryption for instructions to enable In-Use Encryption in libmongoc.
Automatic encryption is an enterprise only feature that only applies to
operations on a collection. Automatic encryption is not supported for
operations on a database or view, and operations that are not bypassed
will result in error. To bypass automatic encryption for all opera-
tions, bypass automatic encryption with
mongoc_auto_encryption_opts_set_bypass_auto_encryption() in opts.
Automatic encryption requires the authenticated user to have the
listCollections privilege action.
Enabling automatic encryption reduces the maximum message size and may
have a negative performance impact.
Only applies to a single-threaded mongoc_client_t. To use with client
pools, see mongoc_client_pool_enable_auto_encryption().
PARAMETERS
+ client: A mongoc_client_t.
+ opts: A required mongoc_auto_encryption_opts_t.
+ error: A bson_error_t which is set on error.
RETURNS
True on success. False on error. On error, error is set.
SEE ALSO:
mongoc_auto_encryption_opts_t
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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_CLIENT_ENABLE_AUTO_ENCRYPTION(3)
mongoc_client_encryption_add_key_alt_name.3
MONGOC_CLIENT_ENCRYPTION_ADD_KEY_ALTiNAME(3)ENT_ENCRYPTION_ADD_KEY_ALT_NAME(3)
SYNOPSIS
bool
mongoc_client_encryption_add_key_alt_name (
mongoc_client_encryption_t *client_encryption,
const bson_value_t *keyid,
const char *keyaltname,
bson_t *key_doc,
bson_error_t *error);
Add keyaltname to the set of alternate names in the key document with
UUID keyid.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t.
+ keyid: A UUID (BSON binary subtype 0x04) key ID of the key to add the
key alternate name to.
+ keyaltname: The key alternate name to add.
+ key_doc: Optional. An uninitialized bson_t set to the value of the
key document before addition of the alternate name, or an empty docu-
ment if the key does not exist. Must be freed by bson_destroy().
+ error: Optional. bson_error_t.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025NT_ENCRYPTION_ADD_KEY_ALT_NAME(3)
mongoc_client_encryption_create_datakey.3
MONGOC_CLIENT_ENCRYPTION_CREATE_DATAKEY(3)ocLIENT_ENCRYPTION_CREATE_DATAKEY(3)
SYNOPSIS
bool
mongoc_client_encryption_create_datakey (
mongoc_client_encryption_t *client_encryption,
const char *kms_provider,
const mongoc_client_encryption_datakey_opts_t *opts,
bson_value_t *keyid,
bson_error_t *error);
Creates a new key document in the key vault collection and sets keyid
to the UUID of the newly created key if keyid is not NULL. The new key
can be used to configure automatic encryption (see
mongoc_client_enable_auto_encryption() and
mongoc_client_pool_enable_auto_encryption()) or for explicit encryption
(see mongoc_client_encryption_encrypt()).
The created key document is inserted into the key vault collection
(identified via mongoc_client_encryption_opts_set_keyvault_namespace())
with majority write concern.
keyid is always initialized (even on error). Caller must call
bson_value_destroy() on keyid to free.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t.
+ kms_provider: A string identifying the Key Management Service (KMS)
provider used to encrypt the datakey (e.g. "aws" or "local").
+ opts: A mongoc_client_encryption_datakey_opts_t
+ keyid: Optional. An uninitialized bson_value_t set to the UUID (BSON
binary subtype 0x04) of the newly created key. Must be freed by
bson_value_destroy().
+ error: Optional. A bson_error_t.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_datakey_opts_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025IENT_ENCRYPTION_CREATE_DATAKEY(3)
mongoc_client_encryption_create_encrypted_collection.3
MONGOC_CLIENT_ENCRYPTIONOCREATELENCRYPTEDgCOLLECTION(3)ENCRYPTED_COLLECTION(3)
SYNOPSIS
mongoc_collection_t*
mongoc_client_encryption_create_encrypted_collection (
mongoc_client_encryption_t *enc,
mongoc_database_t *database,
const char *name,
const bson_t *in_options,
bson_t *out_options,
const char *kms_provider,
const bson_t *opt_masterKey,
bson_error_t *error);
Create a new collection with Queryable Encryption enabled. Requires a
valid mongoc_client_encryption_t object to operate.
New in version 1.24.0.
SEE ALSO:
This function is a convenience API wrapping
mongoc_database_create_collection().
PARAMETERS
+ enc: The mongoc_client_encryption_t to be used to configure encryp-
tion for the new collection.
+ database: The mongoc_database_t in which the new collection will be
created.
+ name: The name of the new collection.
+ in_options: The options for the new collection. (See below).
+ out_options: An optional output option for the final create-collec-
tion options. Should point to storage for a bson_t. The pointed-to
object must be destroyed by the caller. If NULL, has no effect.
+ kms_provider: The name of the KMS provider to use for generating new
data encryption keys for encrypted fields within the collection.
+ opt_masterKey: If provided, used as the masterkey option when data
encryption keys need to be created. (See:
mongoc_client_encryption_datakey_opts_set_masterkey())
+ error: Optional output parameter pointing to storage for a
bson_error_t. If an error occurs, will be initialized with error in-
formation.
RETURNS
If successful, this function returns a new mongoc_collection_t object.
Upon failure, returns NULL and initializes *error with an error indi-
cating the reason for failure. The returned collection object must be
freed by the caller.
CREATION OPTIONS
The in_options parameter behaves similarly to the opts parameter for
mongoc_database_create_collection(), which accepts the options for the
create MongoDB command (Documented here). The in_options document ac-
cepted here is different in one important way:
The $.encryptedFields.fields array is required by this function, and,
unlike the schema documented for the create command, accepts a value of
null for the keyId parameter on each array element.
This function has the following as-if effect:
1. A new set of options O will be created based on in_options.
2. For each element F in the $.encryptedFields.fields array of O:
1. If F contains a "keyId": null element, a new data encryption key
K_f will be created as-if by calling the
mongoc_client_encryption_create_datakey(), using the relevant ar-
guments that were given to mongoc_client_encryption_create_en-
crypted_collection.
2. The ID of K_f will be used to replace the "keyId": null element
within F.
3. A collection will be created using the options O.
4. If out_options is not NULL, O will be written to out_options.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIMay_12,R2025ON_CREATE_ENCRYPTED_COLLECTION(3)
mongoc_client_encryption_datakey_opts_destroy.3
MONGOC_CLIENT_ENCRYPTION_DATAKEYNOPTSbDESTROY(3)YPTION_DATAKEY_OPTS_DESTROY(3)
SYNOPSIS
void
mongoc_client_encryption_datakey_opts_destroy (mongoc_client_encryption_datakey_opts_t *opts);
Frees resources of a mongoc_client_encryption_datakey_opts_t created
with mongoc_client_encryption_datakey_opts_new(). Does nothing if NULL
is passed.
PARAMETERS
+ opts: A mongoc_client_encryption_datakey_opts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,E2025NCRYPTION_DATAKEY_OPTS_DESTROY(3)
mongoc_client_encryption_datakey_opts_new.3
MONGOC_CLIENT_ENCRYPTION_DATAKEY_OPTSbNEW(3)ENT_ENCRYPTION_DATAKEY_OPTS_NEW(3)
SYNOPSIS
mongoc_client_encryption_datakey_opts_t *
mongoc_client_encryption_datakey_opts_new (void);
RETURNS
A new mongoc_client_encryption_datakey_opts_t that must be freed with
mongoc_client_encryption_datakey_opts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025NT_ENCRYPTION_DATAKEY_OPTS_NEW(3)
mongoc_client_encryption_datakey_opts_set_keyaltnames.3
MONGOC_CLIENT_ENCRYPTIONNDATAKEYEOPTSbSETgKEYALTNAMES(3)PTS_SET_KEYALTNAMES(3)
SYNOPSIS
void
mongoc_client_encryption_datakey_opts_set_keyaltnames (
mongoc_client_encryption_datakey_opts_t *opts,
char **keyaltnames,
uint32_t keyaltnames_count);
Sets a list of alternate name strings that can be used to identify a
data key. Key alternate names must be unique.
PARAMETERS
+ opts: A mongoc_client_encryption_datakey_opts_t
+ keyaltnames: An array of strings.
+ keyaltnames_count: The number of strings in keyaltnames.
SEE ALSO:
mongoc_client_encryption_encrypt_opts_set_keyaltname()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIEMayE12,Y2025N_DATAKEY_OPTS_SET_KEYALTNAMES(3)
mongoc_client_encryption_datakey_opts_set_keymaterial.3
MONGOC_CLIENT_ENCRYPTIONNDATAKEYEOPTSbSETgKEYMATERIAL(3)PTS_SET_KEYMATERIAL(3)
SYNOPSIS
void
mongoc_client_encryption_datakey_opts_set_keymaterial (
mongoc_client_encryption_datakey_opts_t *opts,
const uint8_t *data,
uint32_t len);
Sets the custom key material to be used by the data key for encryption
and decryption.
PARAMETERS
+ opts: A mongoc_client_encryption_datakey_opts_t
+ data: A pointer to the bytes constituting the custom key material.
+ len: The length of the bytes constituting the custom key material.
DESCRIPTION
Key material is used to encrypt and decrypt data. If custom key mate-
rial is not provided, the key material for the new data key is gener-
ated from a cryptographically secure random device.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIEMayE12,Y2025N_DATAKEY_OPTS_SET_KEYMATERIAL(3)
mongoc_client_encryption_datakey_opts_set_masterkey.3
MONGOC_CLIENT_ENCRYPTIONMDATAKEYLOPTSbSETgMASTERKEY(3)EY_OPTS_SET_MASTERKEY(3)
SYNOPSIS
void
mongoc_client_encryption_datakey_opts_set_masterkey (
mongoc_client_encryption_datakey_opts_t *opts, const bson_t *masterkey);
Identifies the masterkey for the Key Management Service (KMS) provider
used to encrypt a new data key.
PARAMETERS
+ opts: A mongoc_client_encryption_datakey_opts_t
+ masterkey: A bson_t document describing the KMS provider specific
masterkey.
DESCRIPTION
Setting the masterkey is required when creating a data key with the KMS
provider types: aws, azure, gcp, and kmip.
Setting the masterkey is prohibited with the KMS provider type local.
The format of masterkey for the KMS provider type aws is as follows:
{
region: String,
key: String, /* The Amazon Resource Name (ARN) to the AWS customer master key (CMK). */
endpoint: Optional<String> /* An alternate host identifier to send KMS requests to. May include port number. Defaults to "kms.<region>.amazonaws.com" */
}
The format of masterkey for the KMS provider type azure is as follows:
{
keyVaultEndpoint: String, /* Host with optional port. Example: "example.vault.azure.net". */
keyName: String,
keyVersion: Optional<String> /* A specific version of the named key, defaults to using the key's primary version. */
}
The format of masterkey for the KMS provider type gcp is as follows:
{
projectId: String,
location: String,
keyRing: String,
keyName: String,
keyVersion: Optional<String>, /* A specific version of the named key, defaults to using the key's primary version. */
endpoint: Optional<String> /* Host with optional port. Defaults to "cloudkms.googleapis.com". */
}
The format of masterkey for the KMS provider type kmip is as follows:
{
keyId: Optional<String>,
delegated: Optional<Boolean>, /* If true (recommended), the KMIP server must decrypt this key. Defaults to false. */
endpoint: Optional<String> /* Host with optional port. */
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLMayT12,C2025ION_DATAKEY_OPTS_SET_MASTERKEY(3)
mongoc_client_encryption_datakey_opts_t.3
MONGOC_CLIENT_ENCRYPTION_DATAKEY_OPTSbT(3)ocLIENT_ENCRYPTION_DATAKEY_OPTS_T(3)
SYNOPSIS
typedef struct _mongoc_client_encryption_datakey_opts_t mongoc_client_encryption_datakey_opts_t;
Used to set options for mongoc_client_encryption_create_datakey().
SEE ALSO:
mongoc_client_encryption_create_datakey()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025IENT_ENCRYPTION_DATAKEY_OPTS_T(3)
mongoc_client_encryption_delete_key.3
MONGOC_CLIENT_ENCRYPTION_DELETE_KEY(3)mongocOC_CLIENT_ENCRYPTION_DELETE_KEY(3)
SYNOPSIS
bool
mongoc_client_encryption_delete_key (
mongoc_client_encryption_t *client_encryption,
const bson_value_t *keyid,
bson_t *reply,
bson_error_t *error);
Delete a key document in the key vault collection that has the given
keyid.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t.
+ keyid: The UUID (BSON binary subtype 0x04) of the key to delete.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: Optional. bson_error_t.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_t
mongoc_client_encryption_create_datakey()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_CLIENT_ENCRYPTION_DELETE_KEY(3)
mongoc_client_encryption_destroy.3
MONGOC_CLIENT_ENCRYPTION_DESTROY(3)libmongocONGOC_CLIENT_ENCRYPTION_DESTROY(3)
SYNOPSIS
void
mongoc_client_encryption_destroy (
mongoc_client_encryption_t *client_encryption);
Release all resources associated with client_encryption and free the
structure. Does nothing if client_encryption is NULL.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_CLIENT_ENCRYPTION_DESTROY(3)
mongoc_client_encryption_encrypt.3
MONGOC_CLIENT_ENCRYPTION_ENCRYPT(3)libmongocONGOC_CLIENT_ENCRYPTION_ENCRYPT(3)
SYNOPSIS
bool
mongoc_client_encryption_encrypt (
mongoc_client_encryption_t *client_encryption,
const bson_value_t *value,
mongoc_client_encryption_encrypt_opts_t *opts,
bson_value_t *ciphertext,
bson_error_t *error);
Performs explicit encryption.
ciphertext is always initialized (even on failure). Caller must call
bson_value_destroy() to free.
To insert or query with an "Indexed" or "Range" encrypted payload, use
a mongoc_client_t configured with mongoc_auto_encryption_opts_t. The
mongoc_auto_encryption_opts_t may be configured to bypass query analy-
sis with mongoc_auto_encryption_opts_set_bypass_query_analysis(). The
mongoc_auto_encryption_opts_t must not be configured to bypass auto-
matic encryption with
mongoc_auto_encryption_opts_set_bypass_auto_encryption().
To insert with a Range payload
mongoc_client_encryption_encrypt_range_opts_t must be set in opts.
To query with a Range payload, use
mongoc_client_encryption_encrypt_expression()
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t
+ value: The value to encrypt.
+ opts: A mongoc_client_encryption_encrypt_opts_t.
+ ciphertext: A bson_value_t for the resulting ciphertext (a BSON bi-
nary with subtype 6).
+ error: A bson_error_t set on failure.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_encrypt_opts_t
mongoc_client_enable_auto_encryption()
mongoc_client_decryption_decrypt()
mongoc_client_encryption_encrypt_expression()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_CLIENT_ENCRYPTION_ENCRYPT(3)
mongoc_client_encryption_encrypt_expression.3
MONGOC_CLIENT_ENCRYPTION_ENCRYPTMEXPRESSION(3)ENCRYPTION_ENCRYPT_EXPRESSION(3)
SYNOPSIS
bool
mongoc_client_encryption_encrypt_expression (
mongoc_client_encryption_t *client_encryption,
const bson_t *expr,
mongoc_client_encryption_encrypt_opts_t *opts,
bson_t *expr_out,
bson_error_t *error);
New in version 1.24.0.
Encrypts a Match Expression or Aggregate Expression to query a range
index.
To query with a Range encrypted payload, use a mongoc_client_t config-
ured with mongoc_auto_encryption_opts_t. The
mongoc_auto_encryption_opts_t may be configured to bypass query analy-
sis with mongoc_auto_encryption_opts_set_bypass_query_analysis(). The
mongoc_auto_encryption_opts_t must not be configured to bypass auto-
matic encryption with
mongoc_auto_encryption_opts_set_bypass_auto_encryption().
To query with a Range payload, expr must be one of the following forms:
1. A Match Expression of the following form:
// $gt may also be $gte. $lt may also be $lte.
// Can include one of $gt/$gte/$lt/$lte. It is not required to include both.
{"$and": [{"<field>": {"$gt": "<value1>"}}, {"<field>": {"$lt": "<value2>" }}]}
2. An Aggregation Expression of this form:
// $gt may also be $gte. $lt may also be $lte
// Can include one of $gt/$gte/$lt/$lte. It is not required to include both.
{"$and": [{"$gt": ["<fieldpath>", "<value1>"]}, {"$lt": ["<fieldpath>", "<value2>"]}]
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t
+ expr: The expression to encrypt.
+ opts: A mongoc_client_encryption_encrypt_opts_t.
+ expr_out: A bson_t for the resulting encrypted expression. expr_out
is always initialized (even on failure). Caller must call
bson_destroy() to free.
+ error: A bson_error_t set on failure.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_encrypt_opts_t
mongoc_client_enable_auto_encryption()
mongoc_client_decryption_decrypt()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,L2025_ENCRYPTION_ENCRYPT_EXPRESSION(3)
mongoc_client_encryption_encrypt_opts_destroy.3
MONGOC_CLIENT_ENCRYPTION_ENCRYPTNOPTSbDESTROY(3)YPTION_ENCRYPT_OPTS_DESTROY(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_opts_destroy (mongoc_client_encryption_encrypt_opts_t *opts);
Frees resources of a mongoc_client_encryption_encrypt_opts_t created
with mongoc_client_encryption_encrypt_opts_new(). Does nothing if NULL
is passed.
PARAMETERS
+ opts: A mongoc_client_encryption_encrypt_opts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,E2025NCRYPTION_ENCRYPT_OPTS_DESTROY(3)
mongoc_client_encryption_encrypt_opts_new.3
MONGOC_CLIENT_ENCRYPTION_ENCRYPT_OPTSbNEW(3)ENT_ENCRYPTION_ENCRYPT_OPTS_NEW(3)
SYNOPSIS
mongoc_client_encryption_encrypt_opts_t *
mongoc_client_encryption_encrypt_opts_new (void);
RETURNS
A new mongoc_client_encryption_encrypt_opts_t that must be freed with
mongoc_client_encryption_encrypt_opts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025NT_ENCRYPTION_ENCRYPT_OPTS_NEW(3)
mongoc_client_encryption_encrypt_opts_set_algorithm.3
MONGOC_CLIENT_ENCRYPTIONMENCRYPTLOPTSbSETgALGORITHM(3)PT_OPTS_SET_ALGORITHM(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_opts_set_algorithm (
mongoc_client_encryption_encrypt_opts_t *opts, const char *algorithm);
#define MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM "AEAD_AES_256_CBC_HMAC_SHA_512-Random"
#define MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
#define MONGOC_ENCRYPT_ALGORITHM_INDEXED "Indexed"
#define MONGOC_ENCRYPT_ALGORITHM_UNINDEXED "Unindexed"
#define MONGOC_ENCRYPT_ALGORITHM_RANGE "Range"
Identifies the algorithm to use for encryption. Valid values of algo-
rithm are:
"AEAD_AES_256_CBC_HMAC_SHA_512-Random"
for randomized encryption. Specific to the Client-Side Field Level
Encryption feature.
"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
for deterministic (queryable) encryption. Specific to the
Client-Side Field Level Encryption feature.
"Indexed"
for indexed encryption. Specific to the Queryable Encryption fea-
ture.
"Unindexed"
for unindexed encryption. Specific to the Queryable Encryption fea-
ture.
"Range"
for range encryption. Specific to the Queryable Encryption feature.
PARAMETERS
+ opts: A mongoc_client_encryption_encrypt_opts_t
+ algorithm: A char * identifying the algorithm.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLMayT12,C2025ION_ENCRYPT_OPTS_SET_ALGORITHM(3)
mongoc_client_encryption_encrypt_opts_set_contention_factor.3
MONGOC_CLIENT_ENCRYPTIONLENCRYPTCOPTSbSETgCONTENTIONSFACTOR(3)ENTION_FACTOR(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_opts_set_contention_factor (
mongoc_client_encryption_encrypt_opts_t *opts, int64_t contention_factor);
New in version 1.22.0.
Sets a contention factor for explicit encryption. Only applies when
the algorithm set by
mongoc_client_encryption_encrypt_opts_set_algorithm() is "Indexed" or
"Range". It is an error to set the contention factor when algorithm is
not "Indexed" or "Range". If contention factor is not supplied, it de-
faults to a value of 0.
PARAMETERS
+ opts: A mongoc_client_encryption_encrypt_opts_t
+ contention_factor: A non-negative contention factor.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIENT_ENCMayT12,_2025YPT_OPTS_SET_CONTENTION_FACTOR(3)
mongoc_client_encryption_encrypt_opts_set_keyaltname.3
MONGOC_CLIENT_ENCRYPTIONOENCRYPTIOPTSbSETgKEYALTNAME(3)_OPTS_SET_KEYALTNAME(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_opts_set_keyaltname (
mongoc_client_encryption_encrypt_opts_t *opts, const char *keyaltname);
Identifies the data key to use for encryption. This option is mutually
exclusive with mongoc_client_encryption_encrypt_opts_set_keyid().
PARAMETERS
+ opts: A mongoc_client_encryption_encrypt_opts_t
+ keyaltname: A string identifying a data key by alternate name.
SEE ALSO:
mongoc_client_encryption_encrypt_opts_set_keyid()
mongoc_client_encryption_datakey_opts_set_keyaltnames()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIMay_12,R2025ON_ENCRYPT_OPTS_SET_KEYALTNAME(3)
mongoc_client_encryption_encrypt_opts_set_keyid.3
MONGOC_CLIENT_ENCRYPTION_ENCRYPTOOPTSbSETgKEYID(3)ON_ENCRYPT_OPTS_SET_KEYID(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_opts_set_keyid (
mongoc_client_encryption_encrypt_opts_t *opts, const bson_value_t *keyid);
Identifies the data key to use for encryption. This option is mutually
exclusive with mongoc_client_encryption_encrypt_opts_set_keyaltname().
PARAMETERS
+ opts: A mongoc_client_encryption_encrypt_opts_t
+ keyid: The UUID (BSON binary subtype 0x04) corresponding to the _id
of the data key.
SEE ALSO:
mongoc_client_encryption_encrypt_opts_set_keyaltname()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayL12,T2025RYPTION_ENCRYPT_OPTS_SET_KEYID(3)
mongoc_client_encryption_encrypt_opts_set_query_type.3
MONGOC_CLIENT_ENCRYPTIONOENCRYPTIOPTSbSETgQUERY_TYPE(3)_OPTS_SET_QUERY_TYPE(3)
SYNOPSIS
#define MONGOC_ENCRYPT_QUERY_TYPE_EQUALITY "equality"
#define MONGOC_ENCRYPT_QUERY_TYPE_RANGE "range"
void mongoc_client_encryption_encrypt_opts_set_query_type (
mongoc_client_encryption_encrypt_opts_t *opts, const char* query_type);
New in version 1.22.0.
Sets a query type for explicit encryption. Currently, the supported
values for query_type are "equality" and "range".
Only applies when the algorithm set by
mongoc_client_encryption_encrypt_opts_set_algorithm() is "Indexed" or
"Range". It is an error to set the query type when algorithm is not
"Indexed" or "Range".
PARAMETERS
+ opts: A mongoc_client_encryption_encrypt_opts_t
+ query_type: A query type to use for explicit encryption.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIMay_12,R2025ON_ENCRYPT_OPTS_SET_QUERY_TYPE(3)
mongoc_client_encryption_encrypt_opts_set_range_opts.3
MONGOC_CLIENT_ENCRYPTIONOENCRYPTIOPTSbSETgRANGE_OPTS(3)_OPTS_SET_RANGE_OPTS(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_opts_set_range_opts (
mongoc_client_encryption_encrypt_opts_t *opts,
const mongoc_client_encryption_encrypt_range_opts_t *range_opts);
New in version 1.24.0.
Sets the range_opts for explicit encryption. Only applies when the al-
gorithm set by mongoc_client_encryption_encrypt_opts_set_algorithm() is
"Range". It is an error to set range_opts when algorithm is not
"Range".
PARAMETERS
+ opts: A mongoc_client_encryption_encrypt_opts_t
+ range_opts: A mongoc_client_encryption_encrypt_range_opts_t
SEE ALSO:
mongoc_client_encryption_encrypt_range_opts_new()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIMay_12,R2025ON_ENCRYPT_OPTS_SET_RANGE_OPTS(3)
mongoc_client_encryption_encrypt_opts_t.3
MONGOC_CLIENT_ENCRYPTION_ENCRYPT_OPTSbT(3)ocLIENT_ENCRYPTION_ENCRYPT_OPTS_T(3)
SYNOPSIS
typedef struct _mongoc_client_encryption_encrypt_opts_t mongoc_client_encryption_encrypt_opts_t;
Used to set options for mongoc_client_encryption_encrypt().
SEE ALSO:
mongoc_client_encryption_encrypt()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025IENT_ENCRYPTION_ENCRYPT_OPTS_T(3)
mongoc_client_encryption_encrypt_range_opts_destroy.3
MONGOC_CLIENT_ENCRYPTIONMENCRYPTLRANGEmOPTScDESTROY(3)PT_RANGE_OPTS_DESTROY(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_range_opts_destroy (mongoc_client_encryption_encrypt_range_opts_t *range_opts);
New in version 1.24.0.
Frees resources of a mongoc_client_encryption_encrypt_range_opts_t cre-
ated with mongoc_client_encryption_encrypt_range_opts_new(). Does noth-
ing if NULL is passed.
PARAMETERS
+ range_opts: A mongoc_client_encryption_encrypt_range_opts_t.
SEE ALSO:
mongoc_client_encryption_encrypt_range_opts_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLMayT12,C2025ION_ENCRYPT_RANGE_OPTS_DESTROY(3)
mongoc_client_encryption_encrypt_range_opts_new.3
MONGOC_CLIENT_ENCRYPTION_ENCRYPTORANGEmOPTScNEW(3)ON_ENCRYPT_RANGE_OPTS_NEW(3)
SYNOPSIS
mongoc_client_encryption_encrypt_range_opts_t *
mongoc_client_encryption_encrypt_range_opts_new (void);
New in version 1.24.0.
RETURNS
A new mongoc_client_encryption_encrypt_range_opts_t that must be freed
with mongoc_client_encryption_encrypt_range_opts_destroy().
SEE ALSO:
mongoc_client_encryption_encrypt_range_opts_t
mongoc_client_encryption_encrypt_range_opts_destroy()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayL12,T2025RYPTION_ENCRYPT_RANGE_OPTS_NEW(3)
mongoc_client_encryption_encrypt_range_opts_set_max.3
MONGOC_CLIENT_ENCRYPTIONMENCRYPTLRANGEmOPTScSETNMAX(3)PT_RANGE_OPTS_SET_MAX(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_range_opts_set_max (
mongoc_client_encryption_encrypt_range_opts_t *range_opts,
const bson_value_t *max);
New in version 1.24.0.
Sets the maximum value of the range for explicit encryption. Only ap-
plies when the algorithm set by
mongoc_client_encryption_encrypt_opts_set_algorithm() is "Range". It
is an error to set maximum when algorithm is not "Range".
The maximum must match the value set in the encryptedFields of the des-
tination collection. It is an error to set a different value.
For double and decimal128 fields, max/max/precision must all be set, or
all be unset.
PARAMETERS
+ range_opts: A mongoc_client_encryption_encrypt_range_opts_t
+ max: The maximum bson value of the range.
SEE ALSO:
mongoc_client_encryption_encrypt_range_opts_set_precision()
mongoc_client_encryption_encrypt_range_opts_set_min()
mongoc_client_encryption_encrypt_range_opts_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLMayT12,C2025ION_ENCRYPT_RANGE_OPTS_SET_MAX(3)
mongoc_client_encryption_encrypt_range_opts_set_min.3
MONGOC_CLIENT_ENCRYPTIONMENCRYPTLRANGEmOPTScSETNMIN(3)PT_RANGE_OPTS_SET_MIN(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_range_opts_set_min (
mongoc_client_encryption_encrypt_range_opts_t *range_opts,
const bson_value_t *min);
New in version 1.24.0.
Sets the minimum value of the range for explicit encryption. Only ap-
plies when the algorithm set by
mongoc_client_encryption_encrypt_opts_set_algorithm() is "Range". It
is an error to set minimum when algorithm is not "Range".
The minimum must match the value set in the encryptedFields of the des-
tination collection. It is an error to set a different value.
For double and decimal128 fields, min/max/precision must all be set, or
all be unset.
PARAMETERS
+ range_opts: A mongoc_client_encryption_encrypt_range_opts_t
+ min: The minimum bson value of the range.
SEE ALSO:
mongoc_client_encryption_encrypt_range_opts_set_precision()
mongoc_client_encryption_encrypt_range_opts_set_max()
mongoc_client_encryption_encrypt_range_opts_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLMayT12,C2025ION_ENCRYPT_RANGE_OPTS_SET_MIN(3)
mongoc_client_encryption_encrypt_range_opts_set_precision.3
MONGOC_CLIENT_ENCRYPTION_ENCRYPTERANGEmOPTScSETYPRECISION(3)S_SET_PRECISION(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_range_opts_set_precision (
mongoc_client_encryption_encrypt_range_opts_t *range_opts, int32_t precision);
New in version 1.24.0.
Sets precision for explicit encryption. Only applies when the algo-
rithm set by mongoc_client_encryption_encrypt_opts_set_algorithm() is
"Range". It is an error to set precision when algorithm is not
"Range".
Precision can only be set with double or decimal128 fields. It is an
error to set precision if the type of the encryptedFields in the desti-
nation collection is not double or decimal128.
For double and decimal128 fields, min/max/precision must all be set, or
all be unset.
Precision must match the value set in the encryptedFields of the desti-
nation collection. It is an error to set a different value.
PARAMETERS
+ range_opts: A mongoc_client_encryption_encrypt_range_opts_t
+ precision: A non-negative precision.
SEE ALSO:
mongoc_client_encryption_encrypt_range_opts_set_min()
mongoc_client_encryption_encrypt_range_opts_set_max()
mongoc_client_encryption_encrypt_range_opts_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIENT_EMayY12,O2025CRYPT_RANGE_OPTS_SET_PRECISION(3)
mongoc_client_encryption_encrypt_range_opts_set_sparsity.3
MONGOC_CLIENT_ENCRYPTIONCENCRYPT_RANGEmOPTScSETRSPARSITY(3)PTS_SET_SPARSITY(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_range_opts_set_sparsity (
mongoc_client_encryption_encrypt_range_opts_t *range_opts, int64_t sparsity);
New in version 1.24.0.
Sets sparsity for explicit encryption. Only applies when the algorithm
set by mongoc_client_encryption_encrypt_opts_set_algorithm() is
"Range". It is an error to set sparsity when algorithm is not "Range".
Sparsity may be used to tune performance. When omitted, a default value
is used.
Sparsity must match the value set in the encryptedFields of the desti-
nation collection. It is an error to set a different value.
PARAMETERS
+ range_opts: A mongoc_client_encryption_encrypt_range_opts_t
+ sparsity: A non-negative sparsity.
SEE ALSO:
mongoc_client_encryption_encrypt_range_opts_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIENT_MayR12,I2025NCRYPT_RANGE_OPTS_SET_SPARSITY(3)
mongoc_client_encryption_encrypt_range_opts_set_trim_factor.3
MONGOC_CLIENT_ENCRYPTIONLENCRYPTCRANGEmOPTScSETTTRIMGFACTOR(3)T_TRIM_FACTOR(3)
SYNOPSIS
void
mongoc_client_encryption_encrypt_range_opts_set_trim_factor (
mongoc_client_encryption_encrypt_range_opts_t *range_opts, int32_t trim_factor);
New in version 1.28.0.
Sets trim factor for explicit encryption. Only applies when the algo-
rithm set by mongoc_client_encryption_encrypt_opts_set_algorithm() is
"Range". It is an error to set trim factor when algorithm is not
"Range".
The trim factor may be used to tune performance. When omitted, a de-
fault value is used.
Trim factor must match the value set in the encryptedFields of the des-
tination collection. It is an error to set a different value.
PARAMETERS
+ range_opts: A mongoc_client_encryption_encrypt_range_opts_t
+ trim_factor: A non-negative trim factor.
SEE ALSO:
mongoc_client_encryption_encrypt_range_opts_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIENT_ENCMayT12,_2025YPT_RANGE_OPTS_SET_TRIM_FACTOR(3)
mongoc_client_encryption_encrypt_range_opts_t.3
MONGOC_CLIENT_ENCRYPTION_ENCRYPTNRANGEmOPTScT(3)YPTION_ENCRYPT_RANGE_OPTS_T(3)
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 sup-
porting "range" queries. Used to set options for
mongoc_client_encryption_encrypt().
The options min, max, trim factor, sparsity, and range must match the
values set in the encryptedFields of the destination collection.
For double and decimal128 fields, min/max/precision must all be set, or
all be unset.
SEE ALSO:
mongoc_client_encryption_encrypt()
mongoc_client_encryption_encrypt_opts_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONMay_12,E2025NCRYPTION_ENCRYPT_RANGE_OPTS_T(3)
mongoc_client_encryption_get_crypt_shared_version.3
MONGOC_CLIENT_ENCRYPTION_GETNCRYPTLSHAREDgVERSION(3)ET_CRYPT_SHARED_VERSION(3)
SYNOPSIS
const char*
mongoc_client_encryption_get_crypt_shared_version (mongoc_client_encryption_t const *enc);
Obtain the version string of the crypt_shared that is loaded for the
given explicit encryption object. If no crypt_shared library is loaded,
the returned pointer will be NULL.
PARAMETERS
+ enc: A live mongoc_client_encryption_t
RETURNS
A pointer to a null-terminated character array string designating the
version of crypt_shared that was loaded for enc. If no crypt_shared li-
brary is loaded, the returned pointer will be NULL. The pointed-to ar-
ray must not be modified or freed. The returned pointer is only valid
for the lifetime of enc.
SEE ALSO:
+ mongoc_client_get_crypt_shared_version()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_MayE12,E2025PTION_GET_CRYPT_SHARED_VERSION(3)
mongoc_client_encryption_get_key.3
MONGOC_CLIENT_ENCRYPTION_GET_KEY(3)libmongocONGOC_CLIENT_ENCRYPTION_GET_KEY(3)
SYNOPSIS
bool
mongoc_client_encryption_get_key (mongoc_client_encryption_t *client_encryption,
const bson_value_t *keyid,
bson_t *key_doc,
bson_error_t *error);
Get a key document in the key vault collection that has the given
keyid.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t.
+ keyid: The UUID (BSON binary subtype 0x04) of the key to get.
+ key_doc: Optional. An uninitialized bson_t set to the resulting key
document, or an empty document value if the key does not exist. Must
be freed by bson_destroy().
+ error: Optional. bson_error_t.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_CLIENT_ENCRYPTION_GET_KEY(3)
mongoc_client_encryption_get_key_by_alt_name.3
MONGOC_CLIENT_ENCRYPTION_GET_KEYOBYlALToNAME(3)CRYPTION_GET_KEY_BY_ALT_NAME(3)
SYNOPSIS
bool
mongoc_client_encryption_get_key_by_alt_name (
mongoc_client_encryption_t *client_encryption,
const char *keyaltname,
bson_value_t *key_doc,
bson_error_t *error);
Get a key document in the key vault collection that has the given
keyaltname.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t.
+ keyaltname: The key alternate name of the key to get.
+ key_doc: Optional. An uninitialized bson_t set to the resulting key
document, or an empty document if the key does not exist. Must be
freed by bson_value_destroy().
+ error: Optional. bson_error_t.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,I2025ENCRYPTION_GET_KEY_BY_ALT_NAME(3)
mongoc_client_encryption_get_keys.3
MONGOC_CLIENT_ENCRYPTION_GET_KEYS(3)ibmongocNGOC_CLIENT_ENCRYPTION_GET_KEYS(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_client_encryption_get_keys (mongoc_client_encryption_t *client_encryption,
bson_error_t *error);
Get all the key documents in the key vault collection.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t.
+ error: Optional. bson_error_t.
RETURNS
Returns the result of the internal find command if successful. Returns
NULL and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_CLIENT_ENCRYPTION_GET_KEYS(3)
mongoc_client_encryption_new.3
MONGOC_CLIENT_ENCRYPTION_NEW(3) libmongoc MONGOC_CLIENT_ENCRYPTION_NEW(3)
SYNOPSIS
mongoc_client_encryption_t *
mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts,
bson_error_t *error);
Create a new mongoc_client_encryption_t.
PARAMETERS
+ opts: A mongoc_client_encryption_opts_t.
+ error: A bson_error_t.
RETURNS
A new mongoc_client_encryption_t that must be freed with
mongoc_client_encryption_destroy() if successful. Returns NULL and sets
error otherwise.
SEE ALSO:
mongoc_client_encryption_t
mongoc_client_encryption_opts_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_ENCRYPTION_NEW(3)
mongoc_client_encryption_opts_destroy.3
MONGOC_CLIENT_ENCRYPTION_OPTS_DESTROY(3)ngoc_CLIENT_ENCRYPTION_OPTS_DESTROY(3)
SYNOPSIS
void
mongoc_client_encryption_opts_destroy (mongoc_client_encryption_opts_t *opts);
Frees resources of a mongoc_client_encryption_opts_t created with
mongoc_client_encryption_opts_new(). Does nothing if NULL is passed.
PARAMETERS
+ opts: A mongoc_client_encryption_opts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025CLIENT_ENCRYPTION_OPTS_DESTROY(3)
mongoc_client_encryption_opts_new.3
MONGOC_CLIENT_ENCRYPTION_OPTS_NEW(3)ibmongocNGOC_CLIENT_ENCRYPTION_OPTS_NEW(3)
SYNOPSIS
mongoc_client_encryption_opts_t *
mongoc_client_encryption_opts_new (void);
RETURNS
A new mongoc_client_encryption_opts_t that must be freed with
mongoc_client_encryption_opts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_CLIENT_ENCRYPTION_OPTS_NEW(3)
mongoc_client_encryption_opts_set_key_expiration.3
MONGOC_CLIENT_ENCRYPTION_OPTSNSET_KEYbEXPIRATION(3)_OPTS_SET_KEY_EXPIRATION(3)
SYNOPSIS
void
mongoc_client_encryption_opts_set_key_expiration (
mongoc_client_encryption_opts_t *opts, uint64_t cache_expiration_ms);
PARAMETERS
+ opts: The mongoc_client_encryption_opts_t
+ cache_expiration_ms: The data encryption key cache expiration time in
milliseconds. Defaults to 60,000. 0 means "never expire".
SEE ALSO:
mongoc_client_encryption_new()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOCMayI12,_2025YPTION_OPTS_SET_KEY_EXPIRATION(3)
mongoc_client_encryption_opts_set_key_vault_namespace.3
MONGOC_CLIENT_ENCRYPTIONNOPTSCSETNKEYbVAULTcNAMESPACE(3)KEY_VAULT_NAMESPACE(3)
SYNOPSIS
void
mongoc_client_encryption_opts_set_keyvault_namespace (
mongoc_client_encryption_opts_t *opts, const char *db, const char *coll);
Set the database and collection name of the key vault. The key vault is
the specially designated collection containing encrypted data keys for
In-Use Encryption.
PARAMETERS
+ opts: The mongoc_client_encryption_opts_t
+ db: The database name of the key vault collection.
+ coll: The collection name of the key vault collection.
SEE ALSO:
mongoc_client_encryption_new()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIEMayE12,Y2025N_OPTS_SET_KEY_VAULT_NAMESPACE(3)
mongoc_client_encryption_opts_set_keyvault_client.3
MONGOC_CLIENT_ENCRYPTION_OPTSGSETCKEYVAULToCLIENT(3)PTS_SET_KEYVAULT_CLIENT(3)
SYNOPSIS
void
mongoc_client_encryption_opts_set_keyvault_client (
mongoc_client_encryption_opts_t *opts,
mongoc_client_t *keyvault_client);
Set the mongoc_client_t to use during key creation and key lookup for
encryption and decryption. This may be either a single-threaded or
multi-threaded client (i.e. a client obtained from a
mongoc_client_pool_t).
PARAMETERS
+ opts: A mongoc_client_encryption_opts_t.
+ client: A mongoc_client_t to use for key lookup and creation. This
client MUST outlive any mongoc_client_encryption_t configured to use
it with mongoc_client_encryption_new().
SEE ALSO:
mongoc_client_encryption_new()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_MayE12,E2025PTION_OPTS_SET_KEYVAULT_CLIENT(3)
mongoc_client_encryption_opts_set_kms_credential_provider_callback.3
MONGOC_CLIENTOENCRYPTIONNOPTSTSET_KMSbCREDENTIALRPROVIDER_CALLBACK(3)LLBACK(3)
New in version 1.23.0.
SYNOPSIS
void
mongoc_client_encryption_opts_set_kms_credential_provider_callback (
mongoc_client_encryption_opts_t *opts,
mongoc_kms_credentials_provider_callback_fn fn,
void *userdata);
Set the user-provided callback to provide KMS credentials on-demand
when they are needed.
PARAMETERS
+ opts - The options object to update.
+ fn - The provider callback to set on the options object. May be NULL
to clear the callback. Refer to:
mongoc_kms_credentials_provider_callback_fn
+ userdata - An arbitrary pointer that will be passed along to the
callback function when it is called by libmongoc.
SEE ALSO:
mongoc_auto_encryption_opts_set_kms_credential_provider_callback()
Related:
type mongoc_kms_credentials_provider_callback_fn
typedef
bool (*mongoc_kms_credentials_provider_callback_fn) (void *userdata,
const bson_t *params,
bson_t *out,
bson_error_t *error);
The type of a callback function for providing KMS providers data
on-demand.
Parameters
+ userdata - The same userdata pointer provided to the
userdata parameter when the callback was set.
+ params - Parameters for the requested KMS credentials.
Currently empty.
+ out - The output bson_t in which to write the new KMS
providers. When passed to the callback, this already
points to an empty BSON document which must be popu-
lated.
+ error - An output parameter for indicating any errors
that might occur while generating the KMS credentials.
Return value
Must return true on success, false on failure.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-devMONGOC_CLIENT_ENCRYPTIONMayT12,E2025S_CREDENTIAL_PROVIDER_CALLBACK(3)
mongoc_client_encryption_opts_set_kms_providers.3
MONGOC_CLIENT_ENCRYPTION_OPTSOSETCKMSbPROVIDERS(3)ON_OPTS_SET_KMS_PROVIDERS(3)
SYNOPSIS
void
mongoc_client_encryption_opts_set_kms_providers (
mongoc_client_encryption_opts_t *opts, const bson_t *kms_providers);
PARAMETERS
+ opts: The mongoc_client_encryption_opts_t
+ kms_providers: A bson_t containing configuration for an external Key
Management Service (KMS).
kms_providers is a BSON document containing configuration for each KMS
provider.
KMS providers are specified as a string of the form <KMS provider type>
or <KMS provider type>:<KMS provider name>. The supported KMS provider
types are aws, azure, gcp, local, and kmip. The optional name enables
configuring multiple KMS providers with the same KMS provider type
(e.g. aws:name1 and aws:name2 can refer to different AWS accounts). At
least one KMS provider must be specified.
The format for the KMS provider type aws is as follows:
aws: {
accessKeyId: String,
secretAccessKey: String
}
The format for the KMS provider type local is as follows:
local: {
key: <96 byte BSON binary of subtype 0> or String /* The master key used to encrypt/decrypt data keys. May be passed as a base64 encoded string. */
}
The format for the KMS provider type azure is as follows:
azure: {
tenantId: String,
clientId: String,
clientSecret: String,
identityPlatformEndpoint: Optional<String> /* Defaults to login.microsoftonline.com */
}
The format for the KMS provider type gcp is as follows:
gcp: {
email: String,
privateKey: byte[] or String, /* May be passed as a base64 encoded string. */
endpoint: Optional<String> /* Defaults to oauth2.googleapis.com */
}
The format for the KMS provider type kmip is as follows:
kmip: {
endpoint: String
}
KMS providers may include an optional name suffix separate with a
colon. This enables configuring multiple KMS providers with the same
KMS provider type. Example:
"aws:name1": {
accessKeyId: String,
secretAccessKey: String
},
"aws:name2": {
accessKeyId: String,
secretAccessKey: String
}
SEE ALSO:
mongoc_client_encryption_new()
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayL12,T2025RYPTION_OPTS_SET_KMS_PROVIDERS(3)
mongoc_client_encryption_opts_set_tls_opts.3
MONGOC_CLIENT_ENCRYPTION_OPTS_SETMTLSbOPTS(3)T_ENCRYPTION_OPTS_SET_TLS_OPTS(3)
SYNOPSIS
void
mongoc_client_encryption_opts_set_tls_opts (
mongoc_client_encryption_opts_t *opts, const bson_t *tls_opts);
PARAMETERS
+ opts: The mongoc_client_encryption_opts_t
+ tls_opts: A bson_t mapping a Key Management Service (KMS) provider to
a BSON document with TLS options.
tls_opts is a BSON document of the following form:
<KMS provider>: {
tlsCaFile: Optional<String>
tlsCertificateKeyFile: Optional<String>
tlsCertificateKeyFilePassword: Optional<String>
}
KMS providers are specified as a string of the form <KMS provider type>
or <KMS provider type>:<KMS provider name>. The supported KMS provider
types are aws, azure, gcp, local, and kmip. The optional name enables
configuring multiple KMS providers with the same KMS provider type
(e.g. aws:name1 and aws:name2 can refer to different AWS accounts).
tls_opts maps the KMS provider to a BSON document for TLS options.
The BSON document for TLS options may contain the following keys:
+ MONGOC_URI_TLSCERTIFICATEKEYFILE
+ MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD
+ MONGOC_URI_TLSCAFILE
Example use
mongoc_client_encryption_opts_t *ce_opts = mongoc_client_encryption_opts_new ();
bson_t *tls_opts = bson_new ();
BCON_APPEND (tls_opts, "kmip", "{", MONGOC_URI_TLSCAFILE, "ca1.pem", "}");
BCON_APPEND (tls_opts, "aws", "{", MONGOC_URI_TLSCAFILE, "ca2.pem", "}");
mongoc_client_encryption_opts_set_tls_opts (ce_opts, tls_opts);
See Configuring TLS for a description of the behavior of these options.
SEE ALSO:
In-Use Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,C2025T_ENCRYPTION_OPTS_SET_TLS_OPTS(3)
mongoc_client_encryption_opts_t.3
MONGOC_CLIENT_ENCRYPTION_OPTS_T(3) libmongocMONGOC_CLIENT_ENCRYPTION_OPTS_T(3)
SYNOPSIS
typedef struct _mongoc_client_encryption_opts_t mongoc_client_encryption_opts_t;
Used to set options for mongoc_client_encryption_new().
SEE ALSO:
mongoc_client_encryption_new()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_CLIENT_ENCRYPTION_OPTS_T(3)
mongoc_client_encryption_remove_key_alt_name.3
MONGOC_CLIENT_ENCRYPTION_REMOVEMKEYlALToNAME(3)CRYPTION_REMOVE_KEY_ALT_NAME(3)
SYNOPSIS
bool
mongoc_client_encryption_remove_key_alt_name (
mongoc_client_encryption_t *client_encryption,
const bson_value_t *keyid,
const char *keyaltname,
bson_t *key_doc,
bson_error_t *error);
Remove keyaltname from the set of keyAltNames in the key document with
UUID keyid.
Also removes the keyAltNames field from the key document if it would
otherwise be empty.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t.
+ keyid: The UUID (BSON binary subtype 0x04) of the key to remove the
key alternate name from.
+ keyaltname: The key alternate name to remove.
+ key_doc: Optional. An uninitialized bson_t set to the value of the
key document before removal of the key alternate name, or an empty
document the key does not exist. Must be freed by
bson_value_destroy().
+ error: Optional. bson_error_t.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,I2025ENCRYPTION_REMOVE_KEY_ALT_NAME(3)
mongoc_client_encryption_rewrap_many_datakey.3
MONGOC_CLIENT_ENCRYPTION_REWRAPMMANYiDATAKEY(3)CRYPTION_REWRAP_MANY_DATAKEY(3)
SYNOPSIS
bool
mongoc_client_encryption_rewrap_many_datakey (
mongoc_client_encryption_t *client_encryption,
const bson_t *filter,
const char *provider,
const bson_t *master_key,
mongoc_client_encryption_rewrap_many_datakey_result_t *result,
bson_error_t *error);
Rewraps zero or more data keys in the key vault collection that match
the provided filter.
A NULL argument for filter is equivalent to being given an empty docu-
ment (match all).
If provider is NULL, rewraps matching data keys with their current KMS
provider and master key.
If provider is not NULL, rewraps matching data keys with the new KMS
provider as described by master_key. The master_key document must con-
form to the Client Side Encryption specification.
PARAMETERS
+ client_encryption: A mongoc_client_encryption_t.
+ filter: The filter to use when finding data keys to rewrap in the key
vault collection.
+ provider: The new KMS provider to use to encrypt the data keys, or
NULL to use the current KMS provider(s).
+ master_key: The master key fields corresponding to the new KMS
provider when provider is not NULL.
+ result: An optional
mongoc_client_encryption_rewrap_many_datakey_result_t.
+ error: A bson_error_t set on failure.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_client_encryption_rewrap_many_datakey_result_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,I2025ENCRYPTION_REWRAP_MANY_DATAKEY(3)
mongoc_client_encryption_rewrap_many_datakey_result_destroy.3
MONGOC_CLIENT_ENCRYPTIONLREWRAPNMANYiDATAKEYRRESULTYDESTROY(3)ESULT_DESTROY(3)
SYNOPSIS
void
mongoc_client_encryption_rewrap_many_datakey_result_destroy (
mongoc_client_encryption_rewrap_many_datakey_result_t *result);
Frees resources of a
mongoc_client_encryption_rewrap_many_datakey_result_t created with
mongoc_client_encryption_rewrap_many_datakey_result_new(). Does nothing
if NULL is passed.
PARAMETERS
+ result: A mongoc_client_encryption_rewrap_many_datakey_result_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIENT_ENCMayT12,_2025AP_MANY_DATAKEY_RESULT_DESTROY(3)
mongoc_client_encryption_rewrap_many_datakey_result_get_bulk_write_result.3
MONGOCOCLIENTNENCRYPTIONOREWRAPAMANYiDATAKEYERESULTLGETEBULKLWRITETRESULT(3)3)
SYNOPSIS
const bson_t *
mongoc_client_encryption_rewrap_many_datakey_result_get_bulk_write_result (
mongoc_client_encryption_rewrap_many_datakey_result_t *result);
Get the bulk write result set by a successful call to
mongoc_client_encryption_rewrap_many_datakey().
Returns NULL if no bulk write operation was executed or if the bulk
write operation was unacknowledged.
PARAMETERS
+ result: A mongoc_client_encryption_rewrap_many_datakey_result_t.
RETURNS
A bson_t that must not be modified or freed if result is not NULL. Oth-
erwise, returns NULL.
SEE ALSO:
mongoc_client_encryption_rewrap_many_datakey()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-devCLIENT_ENCRYPTION_REWRAPMayN12,A2025Y_RESULT_GET_BULK_WRITE_RESULT(3)
mongoc_client_encryption_rewrap_many_datakey_result_new.3
MONGOC_CLIENT_ENCRYPTIONOREWRAPNMANYiDATAKEY_RESULT_NEW(3)ATAKEY_RESULT_NEW(3)
SYNOPSIS
mongoc_client_encryption_rewrap_many_datakey_result_t *
mongoc_client_encryption_rewrap_many_datakey_result_new (void);
RETURNS
A new mongoc_client_encryption_rewrap_many_datakey_result_t that must
be freed with
mongoc_client_encryption_rewrap_many_datakey_result_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIENTMayC12,T2025REWRAP_MANY_DATAKEY_RESULT_NEW(3)
mongoc_client_encryption_rewrap_many_datakey_result_t.3
MONGOC_CLIENT_ENCRYPTIONNREWRAPIMANYiDATAKEYORESULTAT(3)NY_DATAKEY_RESULT_T(3)
SYNOPSIS
typedef struct _mongoc_client_encryption_rewrap_many_datakey_result_t
mongoc_client_encryption_rewrap_many_datakey_result_t;
Used to access the result of
mongoc_client_encryption_rewrap_many_datakey().
SEE ALSO:
mongoc_client_encryption_rewrap_many_datakey()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_CLIEMayE12,Y2025N_REWRAP_MANY_DATAKEY_RESULT_T(3)
mongoc_client_encryption_t.3
MONGOC_CLIENT_ENCRYPTION_T(3) libmongoc MONGOC_CLIENT_ENCRYPTION_T(3)
SYNOPSIS
typedef struct _mongoc_client_encryption_t mongoc_client_encryption_t;
mongoc_client_encryption_t provides utility functions for In-Use En-
cryption.
THREAD SAFETY
mongoc_client_encryption_t is NOT thread-safe and should only be used
in the same thread as the mongoc_client_t that is configured via
mongoc_client_encryption_opts_set_keyvault_client().
LIFECYCLE
The key vault client, configured via
mongoc_client_encryption_opts_set_keyvault_client(), must outlive the
mongoc_client_encryption_t.
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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_ENCRYPTION_T(3)
mongoc_client_find_databases_with_opts.3
MONGOC_CLIENT_FIND_DATABASES_WITH_OPTS(3)gocCLIENT_FIND_DATABASES_WITH_OPTS(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_client_find_databases_with_opts (
mongoc_client_t *client, const bson_t *opts);
Fetches a cursor containing documents, each corresponding to a database
on this MongoDB server.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
PARAMETERS
+ client: A mongoc_client_t.
+ opts: A bson_t containing additional options.
opts may be NULL or a BSON document with additional command options:
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
client, and use mongoc_client_session_append() to add the session to
opts. See the example code for mongoc_client_session_t.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
For a list of all options, see the MongoDB Manual entry on the list-
Databases command.
ERRORS
Use mongoc_cursor_error() on the returned cursor to check for errors.
RETURNS
A cursor where each result corresponds to the server's representation
of a database.
The cursor functions mongoc_cursor_set_limit(),
mongoc_cursor_set_batch_size(), and
mongoc_cursor_set_max_await_time_ms() have no use on the returned cur-
sor.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025LIENT_FIND_DATABASES_WITH_OPTS(3)
mongoc_client_get_collection.3
MONGOC_CLIENT_GET_COLLECTION(3) libmongoc MONGOC_CLIENT_GET_COLLECTION(3)
SYNOPSIS
mongoc_collection_t *
mongoc_client_get_collection (mongoc_client_t *client,
const char *db,
const char *collection);
Get a newly allocated mongoc_collection_t for the collection named col-
lection in the database named db.
TIP:
Collections are automatically created on the MongoDB server upon in-
sertion of the first document. There is no need to create a collec-
tion manually.
PARAMETERS
+ client: A mongoc_client_t.
+ db: The name of the database containing the collection.
+ collection: The name of the collection.
RETURNS
A newly allocated mongoc_collection_t that should be freed with
mongoc_collection_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_GET_COLLECTION(3)
mongoc_client_get_crypt_shared_version.3
MONGOC_CLIENT_GET_CRYPT_SHARED_VERSION(3)gocCLIENT_GET_CRYPT_SHARED_VERSION(3)
SYNOPSIS
const char *
mongoc_client_get_crypt_shared_version (const mongoc_client_t *client);
Obtain the version string of the crypt_shared that is loaded for
auto-encryption on the given client. If no crypt_shared library is
loaded, the returned pointer will be NULL.
PARAMETERS
+ client: A live mongoc_client_t
RETURNS
A pointer to a null-terminated character array string designating the
version of crypt_shared that was loaded for auto-encryption with
client. If no crypt_shared library is loaded, or auto-encryption is not
loaded for the given client, the returned pointer will be NULL. The
pointed-to array must not be modified or freed. The returned pointer is
only valid for the lifetime of client.
SEE ALSO:
+ mongoc_client_encryption_get_crypt_shared_version()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025LIENT_GET_CRYPT_SHARED_VERSION(3)
mongoc_client_get_database.3
MONGOC_CLIENT_GET_DATABASE(3) libmongoc MONGOC_CLIENT_GET_DATABASE(3)
SYNOPSIS
mongoc_database_t *
mongoc_client_get_database (mongoc_client_t *client,
const char *name);
Get a newly allocated mongoc_database_t for the database named name.
TIP:
Databases are automatically created on the MongoDB server upon in-
sertion of the first document into a collection. There is no need to
create a database manually.
PARAMETERS
+ client: A mongoc_client_t.
+ name: The name of the database.
RETURNS
A newly allocated mongoc_database_t that should be freed with
mongoc_database_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_GET_DATABASE(3)
mongoc_client_get_database_names.3
MONGOC_CLIENT_GET_DATABASE_NAMES(3)libmongocONGOC_CLIENT_GET_DATABASE_NAMES(3)
WARNING:
Deprecated since version 1.9.0: Use
mongoc_client_get_database_names_with_opts() instead.
SYNOPSIS
char **
mongoc_client_get_database_names (mongoc_client_t *client, bson_error_t *error);
DESCRIPTION
This function queries the MongoDB server for a list of known databases.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
PARAMETERS
+ client: A mongoc_client_t.
+ error: An optional location for a bson_error_t or NULL.
ERRORS
Errors are propagated via the error parameter.
RETURNS
A NULL terminated vector of NULL-byte terminated strings. The result
should be freed with bson_strfreev().
NULL is returned upon failure and error is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_CLIENT_GET_DATABASE_NAMES(3)
mongoc_client_get_database_names_with_opts.3
MONGOC_CLIENT_GET_DATABASE_NAMES_WITHbOPTS(3)T_GET_DATABASE_NAMES_WITH_OPTS(3)
SYNOPSIS
char **
mongoc_client_get_database_names_with_opts (mongoc_client_t *client,
const bson_t *opts,
bson_error_t *error);
This function queries the MongoDB server for a list of known databases.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
PARAMETERS
+ client: A mongoc_client_t.
+ opts: A bson_t containing additional options.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
client, and use mongoc_client_session_append() to add the session to
opts. See the example code for mongoc_client_session_t.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
For a list of all options, see the MongoDB Manual entry on the list-
Databases command.
ERRORS
Errors are propagated via the error parameter.
RETURNS
A NULL terminated vector of NULL-byte terminated strings. The result
should be freed with bson_strfreev().
NULL is returned upon failure and error is set.
EXAMPLES
{
bson_error_t error;
char **strv;
unsigned i;
if ((strv = mongoc_client_get_database_names_with_opts (client, NULL, &error))) {
for (i = 0; strv[i]; i++)
printf ("%s\n", strv[i]);
bson_strfreev (strv);
} else {
fprintf (stderr, "Command failed: %s\n", error.message);
}
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,C2025T_GET_DATABASE_NAMES_WITH_OPTS(3)
mongoc_client_get_default_database.3
MONGOC_CLIENT_GET_DEFAULT_DATABASE(3)bmongocGOC_CLIENT_GET_DEFAULT_DATABASE(3)
SYNOPSIS
mongoc_database_t *
mongoc_client_get_default_database (mongoc_client_t *client);
Get the database named in the MongoDB connection URI, or NULL if the
URI specifies none.
Useful when you want to choose which database to use based only on the
URI in a configuration file.
PARAMETERS
+ client: A mongoc_client_t.
RETURNS
A newly allocated mongoc_database_t that should be freed with
mongoc_database_destroy().
EXAMPLE
Default Database Example
/* default database is "db_name" */
mongoc_client_t *client = mongoc_client_new ("mongodb://host/db_name");
mongoc_database_t *db = mongoc_client_get_default_database (client);
assert (!strcmp ("db_name", mongoc_database_get_name (db)));
mongoc_database_destroy (db);
mongoc_client_destroy (client);
/* no default database */
client = mongoc_client_new ("mongodb://host/");
db = mongoc_client_get_default_database (client);
assert (!db);
mongoc_client_destroy (client);
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_CLIENT_GET_DEFAULT_DATABASE(3)
mongoc_client_get_gridfs.3
MONGOC_CLIENT_GET_GRIDFS(3) libmongoc MONGOC_CLIENT_GET_GRIDFS(3)
SYNOPSIS
mongoc_gridfs_t *
mongoc_client_get_gridfs (mongoc_client_t *client,
const char *db,
const char *prefix,
bson_error_t *error);
The mongoc_client_get_gridfs() function shall create a new
mongoc_gridfs_t. The db parameter is the name of the database which the
gridfs instance should exist in. The prefix parameter corresponds to
the gridfs collection namespacing; its default is "fs", thus the de-
fault GridFS collection names are "fs.files" and "fs.chunks".
PARAMETERS
+ client: A mongoc_client_t.
+ db: The database name.
+ prefix: Optional prefix for gridfs collection names or NULL.
+ error: An optional location for a bson_error_t or NULL.
ERRORS
Errors are propagated via the error parameter.
RETURNS
On success, returns a mongoc_gridfs_t you must free with
mongoc_gridfs_destroy(). Returns NULL upon failure and sets error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_GET_GRIDFS(3)
mongoc_client_get_handshake_description.3
MONGOC_CLIENT_GET_HANDSHAKE_DESCRIPTION(3)ocLIENT_GET_HANDSHAKE_DESCRIPTION(3)
SYNOPSIS
mongoc_server_description_t *
mongoc_client_get_handshake_description (mongoc_client_t *client,
uint32_t server_id,
bson_t *opts,
bson_error_t *error);
Returns a description constructed from the initial handshake response
to a server.
DESCRIPTION
mongoc_client_get_handshake_description() is distinct from
mongoc_client_get_server_description().
mongoc_client_get_server_description() returns a server description
constructed from monitoring, which may differ from the server descrip-
tion constructed from the connection handshake.
mongoc_client_get_handshake_description() will attempt to establish a
connection to the server if a connection was not already established.
It will perform the MongoDB handshake and authentication if required.
Use this function only for building a language driver that wraps the C
Driver. When writing applications in C, higher-level functions automat-
ically select a suitable server.
Single-threaded client behavior
Single-threaded clients only have one active connection to each server.
The one connection is used for both monitoring and application opera-
tions. However, the server description returned by
mongoc_client_get_handshake_description() may still differ from the
server description returned by mongoc_client_get_server_description().
Notably, if connected to a load balanced cluster, the server descrip-
tion returned by mongoc_client_get_server_description() will describe
the load balancer server (mongoc_server_description_type() will return
"LoadBalancer"). And the server description returned by
mongoc_client_get_handshake_description() will describe the backing
server.
PARAMETERS
+ client: A mongoc_client_t.
+ server_id: The ID of the server. This can be obtained from the server
description of mongoc_client_select_server().
+ opts: Unused. Pass NULL.
+ error: An optional location for a bson_error_t or NULL.
RETURNS
A mongoc_server_description_t that must be freed with
mongoc_server_description_destroy(). If a connection has not been suc-
cessfully established to a server, returns NULL and error is filled
out.
SEE ALSO
+ mongoc_client_select_server() To select a server from read prefer-
ences.
+ mongoc_client_get_server_description() To obtain the server descrip-
tion from monitoring for a server.
+ mongoc_server_description_type() To obtain the type of server from a
server description.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025IENT_GET_HANDSHAKE_DESCRIPTION(3)
mongoc_client_get_read_concern.3
MONGOC_CLIENT_GET_READ_CONCERN(3) libmongoc MONGOC_CLIENT_GET_READ_CONCERN(3)
SYNOPSIS
const mongoc_read_concern_t *
mongoc_client_get_read_concern (const mongoc_client_t *client);
Retrieve the default read concern configured for the client instance.
The result should not be modified or freed.
PARAMETERS
+ client: A mongoc_client_t.
RETURNS
A mongoc_read_concern_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_CLIENT_GET_READ_CONCERN(3)
mongoc_client_get_read_prefs.3
MONGOC_CLIENT_GET_READ_PREFS(3) libmongoc MONGOC_CLIENT_GET_READ_PREFS(3)
SYNOPSIS
const mongoc_read_prefs_t *
mongoc_client_get_read_prefs (const mongoc_client_t *client);
Retrieves the default read preferences configured for the client in-
stance. The result should not be modified or freed.
PARAMETERS
+ client: A mongoc_client_t.
RETURNS
A mongoc_read_prefs_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_GET_READ_PREFS(3)
mongoc_client_get_server_description.3
MONGOC_CLIENT_GET_SERVER_DESCRIPTION(3)ongocC_CLIENT_GET_SERVER_DESCRIPTION(3)
SYNOPSIS
mongoc_server_description_t *
mongoc_client_get_server_description (
mongoc_client_t *client, uint32_t server_id);
Get information about the server specified by server_id.
PARAMETERS
+ client: A mongoc_client_t.
+ server_id: An opaque id specifying the server.
RETURNS
A mongoc_server_description_t that must be freed with
mongoc_server_description_destroy(). If the server is no longer in the
topology, returns NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_CLIENT_GET_SERVER_DESCRIPTION(3)
mongoc_client_get_server_descriptions.3
MONGOC_CLIENT_GET_SERVER_DESCRIPTIONS(3)ngoc_CLIENT_GET_SERVER_DESCRIPTIONS(3)
SYNOPSIS
mongoc_server_description_t **
mongoc_client_get_server_descriptions (const mongoc_client_t *client,
size_t *n);
Fetches an array of mongoc_server_description_t structs for all known
servers in the topology. Returns no servers until the client connects.
Returns a single server if the client is directly connected, or all
members of a replica set if the client's MongoDB URI includes a "repli-
caSet" option, or all known mongos servers if the MongoDB URI includes
a list of them.
void
show_servers (const mongoc_client_t *client)
{
bson_t *b = BCON_NEW ("ping", BCON_INT32 (1));
bson_error_t error;
bool r;
mongoc_server_description_t **sds;
size_t i, n;
/* ensure client has connected */
r = mongoc_client_command_simple (client, "db", b, NULL, NULL, &error);
if (!r) {
MONGOC_ERROR ("could not connect: %s\n", error.message);
return;
}
sds = mongoc_client_get_server_descriptions (client, &n);
for (i = 0; i < n; ++i) {
printf ("%s\n", mongoc_server_description_host (sds[i])->host_and_port);
}
mongoc_server_descriptions_destroy_all (sds, n);
bson_destroy (&b);
}
PARAMETERS
+ client: A mongoc_client_t.
+ n: Receives the length of the descriptions array.
RETURNS
A newly allocated array that must be freed with
mongoc_server_descriptions_destroy_all().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025CLIENT_GET_SERVER_DESCRIPTIONS(3)
mongoc_client_get_uri.3
MONGOC_CLIENT_GET_URI(3) libmongoc MONGOC_CLIENT_GET_URI(3)
SYNOPSIS
const mongoc_uri_t *
mongoc_client_get_uri (const mongoc_client_t *client);
Fetches the mongoc_uri_t used to create the client.
PARAMETERS
+ client: A mongoc_client_t.
RETURNS
A mongoc_uri_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_GET_URI(3)
mongoc_client_get_write_concern.3
MONGOC_CLIENT_GET_WRITE_CONCERN(3) libmongocMONGOC_CLIENT_GET_WRITE_CONCERN(3)
SYNOPSIS
const mongoc_write_concern_t *
mongoc_client_get_write_concern (const mongoc_client_t *client);
Retrieve the default write concern configured for the client instance.
The result should not be modified or freed.
PARAMETERS
+ client: A mongoc_client_t.
RETURNS
A mongoc_write_concern_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_CLIENT_GET_WRITE_CONCERN(3)
mongoc_client_new.3
MONGOC_CLIENT_NEW(3) libmongoc MONGOC_CLIENT_NEW(3)
SYNOPSIS
mongoc_client_t *
mongoc_client_new (const char *uri_string);
Creates a new mongoc_client_t using the URI string provided.
PARAMETERS
+ uri_string: A string containing the MongoDB connection URI.
RETURNS
A newly allocated mongoc_client_t that should be freed with
mongoc_client_destroy() when no longer in use. On error, NULL is re-
turned and an error or warning will be logged.
SEE ALSO:
mongoc_client_new_from_uri()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_NEW(3)
mongoc_client_new_from_uri.3
MONGOC_CLIENT_NEW_FROM_URI(3) libmongoc MONGOC_CLIENT_NEW_FROM_URI(3)
SYNOPSIS
mongoc_client_t *
mongoc_client_new_from_uri (const mongoc_uri_t *uri);
Creates a new mongoc_client_t using the mongoc_uri_t provided.
PARAMETERS
+ uri: A mongoc_uri_t.
RETURNS
A newly allocated mongoc_client_t that should be freed with
mongoc_client_destroy() when no longer in use. On error, NULL is re-
turned and an error will be logged.
SEE ALSO:
mongoc_client_new_from_uri_with_error()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_NEW_FROM_URI(3)
mongoc_client_new_from_uri_with_error.3
MONGOC_CLIENT_NEW_FROM_URI_WITH_ERROR(3)ngoc_CLIENT_NEW_FROM_URI_WITH_ERROR(3)
SYNOPSIS
mongoc_client_t *
mongoc_client_new_from_uri_with_error (const mongoc_uri_t *uri,
bson_error_t *error);
Creates a new mongoc_client_t using the mongoc_uri_t provided.
PARAMETERS
+ uri: A mongoc_uri_t.
+ error: An optional location for a bson_error_t or NULL.
RETURNS
A newly allocated mongoc_client_t that should be freed with
mongoc_client_destroy() when no longer in use. On error, NULL is re-
turned and error will be populated with the error description.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025CLIENT_NEW_FROM_URI_WITH_ERROR(3)
mongoc_client_pool_destroy.3
MONGOC_CLIENT_POOL_DESTROY(3) libmongoc MONGOC_CLIENT_POOL_DESTROY(3)
SYNOPSIS
void
mongoc_client_pool_destroy (mongoc_client_pool_t *pool);
Release all resources associated with pool, including freeing the
structure.
All mongoc_client_t objects obtained from mongoc_client_pool_pop() from
pool must be pushed back onto the pool with mongoc_client_pool_push()
prior to calling mongoc_client_pool_destroy().
This method is NOT thread safe, and must only be called by one thread.
It should be called once the application is shutting down, and after
all other threads that use clients have been joined.
PARAMETERS
+ pool: A mongoc_client_pool_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_POOL_DESTROY(3)
mongoc_client_pool_enable_auto_encryption.3
MONGOC_CLIENT_POOL_ENABLE_AUTO_ENCRYPTION(3)ENT_POOL_ENABLE_AUTO_ENCRYPTION(3)
SYNOPSIS
bool
mongoc_client_pool_enable_auto_encryption (mongoc_client_pool_t *pool,
mongoc_auto_encryption_opts_t* opts,
bson_error_t* error);
Enable automatic client side encryption on a mongoc_client_pool_t. Re-
quires libmongoc to be built with support for In-Use Encryption. See
In-Use Encryption for instructions to enable In-Use Encryption in lib-
mongoc.
Automatic encryption is an enterprise-only feature that only applies to
operations on a collection. Automatic encryption is not supported for
operations on a database or view, and operations that are not bypassed
will result in error. To bypass automatic encryption for all opera-
tions, bypass automatic encryption with
mongoc_auto_encryption_opts_set_bypass_auto_encryption() in opts.
Automatic encryption requires the authenticated user to have the
listCollections privilege action.
Enabling automatic encryption reduces the maximum message size and may
have a negative performance impact.
PARAMETERS
+ client: A mongoc_client_t.
+ opts: A required mongoc_auto_encryption_opts_t.
+ error: A bson_error_t which is set on error.
RETURNS
Returns true if successful. Returns false and sets error otherwise.
SEE ALSO:
mongoc_auto_encryption_opts_t
mongoc_client_enable_auto_encryption()
In-Use Encryption for libmongoc
The MongoDB Manual for Client-Side Field Level Encryption
The MongoDB Manual for Queryable Encryption
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025NT_POOL_ENABLE_AUTO_ENCRYPTION(3)
mongoc_client_pool_max_size.3
MONGOC_CLIENT_POOL_MAX_SIZE(3) libmongoc MONGOC_CLIENT_POOL_MAX_SIZE(3)
SYNOPSIS
void
mongoc_client_pool_max_size (mongoc_client_pool_t *pool,
uint32_t max_pool_size);
This function sets the maximum number of pooled connections available
from a mongoc_client_pool_t.
PARAMETERS
+ pool: A mongoc_client_pool_t.
+ max_pool_size: The maximum number of connections which shall be
available from the pool.
THREAD SAFETY
This function is safe to call from multiple threads.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_POOL_MAX_SIZE(3)
mongoc_client_pool_new.3
MONGOC_CLIENT_POOL_NEW(3) libmongoc MONGOC_CLIENT_POOL_NEW(3)
SYNOPSIS
mongoc_client_pool_t *
mongoc_client_pool_new (const mongoc_uri_t *uri);
This function creates a new mongoc_client_pool_t using the mongoc_uri_t
provided.
PARAMETERS
+ uri: A mongoc_uri_t.
RETURNS
A newly allocated mongoc_client_pool_t that should be freed with
mongoc_client_pool_destroy() when no longer in use. On error, NULL is
returned and an error may be logged.
SEE ALSO:
mongoc_client_pool_new_with_error()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_POOL_NEW(3)
mongoc_client_pool_new_with_error.3
MONGOC_CLIENT_POOL_NEW_WITH_ERROR(3)ibmongocNGOC_CLIENT_POOL_NEW_WITH_ERROR(3)
SYNOPSIS
mongoc_client_pool_t *
mongoc_client_pool_new_with_error (const mongoc_uri_t *uri,
bson_error_t *error);
This function creates a new mongoc_client_pool_t using the mongoc_uri_t
provided.
PARAMETERS
+ uri: A mongoc_uri_t.
+ error: An optional location for a bson_error_t or NULL.
RETURNS
A newly allocated mongoc_client_pool_t that should be freed with
mongoc_client_pool_destroy() when no longer in use. On error, NULL is
returned and error will be populated with the error description.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_CLIENT_POOL_NEW_WITH_ERROR(3)
mongoc_client_pool_pop.3
MONGOC_CLIENT_POOL_POP(3) libmongoc MONGOC_CLIENT_POOL_POP(3)
SYNOPSIS
mongoc_client_t *
mongoc_client_pool_pop (mongoc_client_pool_t *pool);
Retrieve a mongoc_client_t from the client pool, or create one. The to-
tal number of clients that can be created from this pool is limited by
the URI option "maxPoolSize", default 100. If this number of clients
has been created and all are in use, mongoc_client_pool_pop blocks un-
til another thread returns a client with mongoc_client_pool_push(). If
the "waitQueueTimeoutMS" URI option was specified with a positive
value, then mongoc_client_pool_pop will return NULL when the timeout
expires.
The returned mongoc_client_t must be returned to the pool with
mongoc_client_pool_push().
NOTE:
Return a checked out mongoc_client_t to the pool with
mongoc_client_pool_push() quickly to encourage reuse of clients
among threads.
PARAMETERS
+ pool: A mongoc_client_pool_t.
RETURNS
A mongoc_client_t.
THREAD SAFETY
This function is safe to call from multiple threads.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_POOL_POP(3)
mongoc_client_pool_push.3
MONGOC_CLIENT_POOL_PUSH(3) libmongoc MONGOC_CLIENT_POOL_PUSH(3)
SYNOPSIS
void
mongoc_client_pool_push (mongoc_client_pool_t *pool, mongoc_client_t *client);
This function returns a mongoc_client_t back to the client pool.
PARAMETERS
+ pool: A mongoc_client_pool_t.
+ client: A mongoc_client_t.
THREAD SAFETY
This function is safe to call from multiple threads.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_POOL_PUSH(3)
mongoc_client_pool_set_apm_callbacks.3
MONGOC_CLIENT_POOL_SET_APM_CALLBACKS(3)ongocC_CLIENT_POOL_SET_APM_CALLBACKS(3)
SYNOPSIS
bool
mongoc_client_pool_set_apm_callbacks (mongoc_client_pool_t *pool,
mongoc_apm_callbacks_t *callbacks,
void *context);
Register a set of callbacks to receive Application Performance Monitor-
ing events.
The callbacks are copied by the pool and may be safely destroyed by the
caller after this API call completes. If a context is passed, it is
the application's responsibility to ensure context remains valid for
the lifetime of the pool.
PARAMETERS
+ pool: A mongoc_client_pool_t.
+ callbacks: A mongoc_apm_callbacks_t.
+ context: Optional pointer to include with each event notification.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and logs an error.
THREAD SAFETY
This function can only be called once on a pool, and must be called be-
fore the first call to mongoc_client_pool_pop().
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_CLIENT_POOL_SET_APM_CALLBACKS(3)
mongoc_client_pool_set_appname.3
MONGOC_CLIENT_POOL_SET_APPNAME(3) libmongoc MONGOC_CLIENT_POOL_SET_APPNAME(3)
SYNOPSIS
bool
mongoc_client_pool_set_appname (mongoc_client_pool_t *pool, const char *appname)
This function is identical to mongoc_client_set_appname() except for
client pools.
Also note that mongoc_client_set_appname() cannot be called on a client
retrieved from a client pool.
PARAMETERS
+ pool: A mongoc_client_pool_t.
+ appname: The application name, of length at most MONGOC_HAND-
SHAKE_APPNAME_MAX.
RETURNS
Returns true if appname was set. If appname is too long, returns false
and logs an error.
THREAD SAFETY
This function can only be called once on a pool, and must be called be-
fore the first call to mongoc_client_pool_pop().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_CLIENT_POOL_SET_APPNAME(3)
mongoc_client_pool_set_error_api.3
MONGOC_CLIENT_POOL_SET_ERROR_API(3)libmongocONGOC_CLIENT_POOL_SET_ERROR_API(3)
SYNOPSIS
bool
mongoc_client_pool_set_error_api (mongoc_client_pool_t *client,
int32_t version);
Configure how the C Driver reports errors. See Setting the Error API
Version.
PARAMETERS
+ pool: A mongoc_client_pool_t.
+ version: The version of the error API, either MONGOC_ERROR_API_VER-
SION_LEGACY or MONGOC_ERROR_API_VERSION_2.
RETURNS
Returns true if the error API version was set, or logs an error message
and returns false if version is invalid.
THREAD SAFETY
This function can only be called once on a pool, and must be called be-
fore the first call to mongoc_client_pool_pop().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_CLIENT_POOL_SET_ERROR_API(3)
mongoc_client_pool_set_server_api.3
MONGOC_CLIENT_POOL_SET_SERVER_API(3)ibmongocNGOC_CLIENT_POOL_SET_SERVER_API(3)
SYNOPSIS
bool
mongoc_client_pool_set_server_api (mongoc_client_pool_t *pool,
const mongoc_server_api_t *api,
bson_error_t *error);
Set the API version to use for clients created through pool. Once the
API version is set on a pool, it may not be changed to a new value. At-
tempting to do so will cause this method to fail and set error.
PARAMETERS
+ pool: A mongoc_client_pool_t.
+ api: A mongoc_server_api_t.
+ error: A bson_error_t.
RETURNS
True if the version was successfully set, false if not. On failure, er-
ror will be set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_CLIENT_POOL_SET_SERVER_API(3)
mongoc_client_pool_set_ssl_opts.3
MONGOC_CLIENT_POOL_SET_SSL_OPTS(3) libmongocMONGOC_CLIENT_POOL_SET_SSL_OPTS(3)
SYNOPSIS
#ifdef MONGOC_ENABLE_SSL
void
mongoc_client_pool_set_ssl_opts (mongoc_client_pool_t *pool,
const mongoc_ssl_opt_t *opts);
#endif
NOTE:
Though some API names include the term "ssl", the C driver only sup-
port TLS protocols, which supersede SSL.
This function is identical to mongoc_client_set_ssl_opts() except for
client pools. It ensures that all clients retrieved from
mongoc_client_pool_pop() or mongoc_client_pool_try_pop() are configured
with the same TLS settings.
The mongoc_ssl_opt_t struct is copied by the pool along with the
strings it points to (pem_file, pem_pwd, ca_file, ca_dir, and crl_file)
so they don't have to remain valid after the call to
mongoc_client_pool_set_ssl_opts().
A call to mongoc_client_pool_set_ssl_opts() overrides all TLS options
set through the connection string with which the mongoc_client_pool_t
was constructed.
PARAMETERS
+ pool: A mongoc_client_pool_t.
+ opts: A mongoc_ssl_opt_t.
THREAD SAFETY
This function can only be called once on a pool, and must be called be-
fore the first call to mongoc_client_pool_pop().
AVAILABILITY
This feature requires that the MongoDB C driver was compiled with -DEN-
ABLE_SSL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_CLIENT_POOL_SET_SSL_OPTS(3)
mongoc_client_pool_set_structured_log_opts.3
MONGOC_CLIENT_POOL_SET_STRUCTUREDMLOGbOPTS(3)T_POOL_SET_STRUCTURED_LOG_OPTS(3)
SYNOPSIS
bool
mongoc_client_pool_set_structured_log_opts (mongoc_client_pool_t *pool,
const mongoc_structured_log_opts_t *opts);
Reconfigures this client pool's structured logging subsystem. See
Structured Logging.
The mongoc_structured_log_opts_t is copied by the pool and may be
safely destroyed by the caller after this API call completes. The ap-
plication is responsible for ensuring any user_data referenced by opts
remains valid for the lifetime of the pool.
By default, the mongoc_client_pool_t will have log options captured
from the environment during mongoc_client_pool_new(). See
mongoc_structured_log_opts_new() for a list of the supported options.
The structured logging subsystem may be disabled by passing NULL as
opts or equivalently by passing NULL as the
mongoc_structured_log_func_t in
mongoc_structured_log_opts_set_handler().
PARAMETERS
+ pool: A mongoc_client_pool_t.
+ opts: A mongoc_structured_log_opts_t allocated with
mongoc_structured_log_opts_new(), or NULL to disable structured log-
ging.
RETURNS
Returns true when used correctly. If called multiple times per pool or
after the first client is initialized, returns false and logs a warn-
ing.
THREAD SAFETY
This function can only be called once on a pool, and must be called be-
fore the first call to mongoc_client_pool_pop().
Thread safety within the handler is the application's responsibility.
Handlers may be invoked concurrently by multiple pool users.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,C2025T_POOL_SET_STRUCTURED_LOG_OPTS(3)
mongoc_client_pool_t.3
MONGOC_CLIENT_POOL_T(3) libmongoc MONGOC_CLIENT_POOL_T(3)
A connection pool for multi-threaded programs. See Connection Pooling.
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, except for its destructor method,
mongoc_client_pool_destroy(), which is not thread-safe and must only be
called from one thread.
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: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
pool = mongoc_client_pool_new (uri);
mongoc_client_pool_set_error_api (pool, 2);
for (i = 0; i < 10; i++) {
pthread_create (&threads[i], NULL, worker, pool);
}
sleep (10);
pthread_mutex_lock (&mutex);
in_shutdown = true;
pthread_mutex_unlock (&mutex);
for (i = 0; i < 10; i++) {
pthread_join (threads[i], &ret);
}
mongoc_client_pool_destroy (pool);
mongoc_uri_destroy (uri);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_POOL_T(3)
mongoc_client_pool_try_pop.3
MONGOC_CLIENT_POOL_TRY_POP(3) libmongoc MONGOC_CLIENT_POOL_TRY_POP(3)
SYNOPSIS
mongoc_client_t *
mongoc_client_pool_try_pop (mongoc_client_pool_t *pool);
This function is identical to mongoc_client_pool_pop() except it will
return NULL instead of blocking for a client to become available.
NOTE:
Return a checked out mongoc_client_t to the pool with
mongoc_client_pool_push() quickly to encourage reuse of clients
among threads.
PARAMETERS
+ pool: A mongoc_client_pool_t.
RETURNS
A mongoc_client_t if one is immediately available, otherwise NULL.
THREAD SAFETY
This function is safe to call from multiple threads.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_POOL_TRY_POP(3)
mongoc_client_read_command_with_opts.3
MONGOC_CLIENT_READ_COMMAND_WITH_OPTS(3)ongocC_CLIENT_READ_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_client_read_command_with_opts (mongoc_client_t *client,
const char *db_name,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, applying logic that is specific to
commands that read, and taking the MongoDB server version into account.
To send a raw command to the server without any of this logic, use
mongoc_client_command_simple().
Use this function for commands that read such as "count" or "distinct".
Read preferences, read concern, and collation can be overridden by var-
ious sources. In a transaction, read concern and write concern are pro-
hibited in opts and the read preference must be primary or NULL. The
highest-priority sources for these options are listed first in the fol-
lowing table. No write concern is applied.
+-----------------+--------------+-----------+
|Read Preferences | Read Concern | Collation |
+-----------------+--------------+-----------+
|read_prefs | opts | opts |
+-----------------+--------------+-----------+
|Transaction | Transaction | |
+-----------------+--------------+-----------+
|client | | |
+-----------------+--------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
reply is always initialized, and must be freed with bson_destroy().
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
Retry logic occurs regardless of the underlying command. Retrying
mapReduce has the potential for degraded performance. Retrying a get-
More command has the potential to miss results. For those commands, use
generic command helpers (like mongoc_client_command_with_opts()) in-
stead.
PARAMETERS
+ client: A mongoc_client_t.
+ db_name: The name of the database to run the command on.
+ command: A bson_t containing the command specification.
+ read_prefs: An optional mongoc_read_prefs_t.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
client, and use mongoc_client_session_append() to add the session to
opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
EXAMPLE
example-command-with-opts.c
/*
Demonstrates how to prepare options for mongoc_client_read_command_with_opts and
mongoc_client_write_command_with_opts. First it calls "cloneCollectionAsCapped"
command with "writeConcern" option, then "distinct" command with "collation" and
"readConcern" options,
Start a MongoDB 3.4 replica set with --enableMajorityReadConcern and insert two
documents:
$ mongo
MongoDB Enterprise replset:PRIMARY> db.my_collection.insert({x: 1, y: "One"})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise replset:PRIMARY> db.my_collection.insert({x: 2, y: "Two"})
WriteResult({ "nInserted" : 1 })
Build and run the example:
gcc example-command-with-opts.c -o example-command-with-opts $(pkg-config
--cflags --libs libmongoc-1.0)
./example-command-with-opts [CONNECTION_STRING]
cloneCollectionAsCapped: { "ok" : 1 }
distinct: { "values" : [ 1, 2 ], "ok" : 1 }
*/
#include <mongoc/mongoc.h>
#include <stdio.h>
#include <stdlib.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
const char *uri_string = "mongodb://127.0.0.1/?appname=client-example";
mongoc_uri_t *uri;
bson_t *cmd;
bson_t *opts;
mongoc_write_concern_t *write_concern;
mongoc_read_prefs_t *read_prefs;
mongoc_read_concern_t *read_concern;
bson_t reply;
bson_error_t error;
char *json;
mongoc_init ();
if (argc > 1) {
uri_string = argv[1];
}
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
client = mongoc_client_new_from_uri (uri);
if (!client) {
return EXIT_FAILURE;
}
mongoc_client_set_error_api (client, 2);
cmd = BCON_NEW ("cloneCollectionAsCapped",
BCON_UTF8 ("my_collection"),
"toCollection",
BCON_UTF8 ("my_capped_collection"),
"size",
BCON_INT64 (1024 * 1024));
/* include write concern "majority" in command options */
write_concern = mongoc_write_concern_new ();
mongoc_write_concern_set_wmajority (write_concern, 10000 /* wtimeoutMS */);
opts = bson_new ();
mongoc_write_concern_append (write_concern, opts);
if (mongoc_client_write_command_with_opts (client, "test", cmd, opts, &reply, &error)) {
json = bson_as_canonical_extended_json (&reply, NULL);
printf ("cloneCollectionAsCapped: %s\n", json);
bson_free (json);
} else {
fprintf (stderr, "cloneCollectionAsCapped: %s\n", error.message);
}
bson_free (cmd);
bson_free (opts);
/* distinct values of "x" in "my_collection" where "y" sorts after "one" */
cmd = BCON_NEW ("distinct",
BCON_UTF8 ("my_collection"),
"key",
BCON_UTF8 ("x"),
"query",
"{",
"y",
"{",
"$gt",
BCON_UTF8 ("one"),
"}",
"}");
read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
/* "One" normally sorts before "one"; make "One" sort after "one" */
opts = BCON_NEW ("collation", "{", "locale", BCON_UTF8 ("en_US"), "caseFirst", BCON_UTF8 ("lower"), "}");
/* add a read concern to "opts" */
read_concern = mongoc_read_concern_new ();
mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_MAJORITY);
mongoc_read_concern_append (read_concern, opts);
if (mongoc_client_read_command_with_opts (client, "test", cmd, read_prefs, opts, &reply, &error)) {
json = bson_as_canonical_extended_json (&reply, NULL);
printf ("distinct: %s\n", json);
bson_free (json);
} else {
fprintf (stderr, "distinct: %s\n", error.message);
}
bson_destroy (cmd);
bson_destroy (opts);
bson_destroy (&reply);
mongoc_read_prefs_destroy (read_prefs);
mongoc_read_concern_destroy (read_concern);
mongoc_write_concern_destroy (write_concern);
mongoc_uri_destroy (uri);
mongoc_client_destroy (client);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_CLIENT_READ_COMMAND_WITH_OPTS(3)
mongoc_client_read_write_command_with_opts.3
MONGOC_CLIENT_READ_WRITE_COMMAND_WITHbOPTS(3)T_READ_WRITE_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_client_read_write_command_with_opts (
mongoc_client_t *client,
const char *db_name,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs /* UNUSED */,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, applying logic for commands that both
read and write, and taking the MongoDB server version into account. To
send a raw command to the server without any of this logic, use
mongoc_client_command_simple().
Use this function for commands that both read and write, such as
"mapReduce" with an output collection.
Read and write concern and collation can be overridden by various
sources. In a transaction, read concern and write concern are prohib-
ited in opts. The highest-priority sources for these options are listed
first in the following table. Read preferences are not applied. The
write concern is omitted for MongoDB before 3.4.
+-------------+---------------+-----------+
|Read Concern | Write Concern | Collation |
+-------------+---------------+-----------+
|opts | opts | opts |
+-------------+---------------+-----------+
|Transaction | Transaction | |
+-------------+---------------+-----------+
|client | client | |
+-------------+---------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
reply is always initialized, and must be freed with bson_destroy().
(The mongoc_read_prefs_t parameter was included by mistake when this
function was introduced in libmongoc 1.5. A command that writes must
not obey a read preference.)
PARAMETERS
+ client: A mongoc_client_t.
+ db_name: The name of the database to run the command on.
+ command: A bson_t containing the command specification.
+ read_prefs: Ignored.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
client, and use mongoc_client_session_append() to add the session to
opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,C2025T_READ_WRITE_COMMAND_WITH_OPTS(3)
mongoc_client_reset.3
MONGOC_CLIENT_RESET(3) libmongoc MONGOC_CLIENT_RESET(3)
SYNOPSIS
void
mongoc_client_reset (mongoc_client_t *client);
Call this method in the child after forking to invalidate the
mongoc_client_t.
DESCRIPTION
Calling mongoc_client_reset() prevents resource cleanup in the child
process from interfering with the parent process.
This method causes the client to clear its session pool without sending
endSessions. It also increments an internal generation counter on the
given client. After this method is called, cursors from previous gener-
ations will not issue a killCursors command when they are destroyed.
Client sessions from previous generations cannot be used and should be
destroyed.
PARAMETERS
+ client: A mongoc_client_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_RESET(3)
mongoc_client_select_server.3
MONGOC_CLIENT_SELECT_SERVER(3) libmongoc MONGOC_CLIENT_SELECT_SERVER(3)
SYNOPSIS
mongoc_server_description_t *
mongoc_client_select_server (mongoc_client_t *client,
bool for_writes,
const mongoc_read_prefs_t *prefs,
bson_error_t *error);
Choose a server for an operation, according to the logic described in
the Server Selection Spec.
Use this function only for building a language driver that wraps the C
Driver. When writing applications in C, higher-level functions automat-
ically select a suitable server.
PARAMETERS
+ client: A mongoc_client_t.
+ for_writes: Whether to choose a server suitable for writes or reads.
+ prefs: An optional mongoc_read_prefs_t. If for_writes is true, prefs
must be NULL. Otherwise, use prefs to customize server selection, or
pass NULL to use read preference PRIMARY.
+ error: An optional location for a bson_error_t or NULL.
RETURNS
A mongoc_server_description_t that must be freed with
mongoc_server_description_destroy(). If no suitable server is found,
returns NULL and error is filled out.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_SELECT_SERVER(3)
mongoc_client_session_abort_transaction.3
MONGOC_CLIENT_SESSION_ABORT_TRANSACTION(3)ocLIENT_SESSION_ABORT_TRANSACTION(3)
SYNOPSIS
bool
mongoc_client_session_abort_transaction (mongoc_client_session_t *session,
bson_error_t *error);
Abort a multi-document transaction.
PARAMETERS
+ session: A mongoc_client_session_t.
+ error: An optional location for a bson_error_t or NULL.
RETURN
Returns true if the transaction was aborted. Returns false and sets er-
ror if there are invalid arguments, such as a session with no transac-
tion in progress. Network or server errors are ignored.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025IENT_SESSION_ABORT_TRANSACTION(3)
mongoc_client_session_advance_cluster_time.3
MONGOC_CLIENT_SESSION_ADVANCE_CLUSTERbTIME(3)T_SESSION_ADVANCE_CLUSTER_TIME(3)
SYNOPSIS
void
mongoc_client_session_advance_cluster_time (mongoc_client_session_t *session,
const bson_t *cluster_time);
Advance the cluster time for a session. Has an effect only if the new
cluster time is greater than the session's current cluster time.
Use mongoc_client_session_advance_operation_time() and
mongoc_client_session_advance_cluster_time() to copy the operationTime
and clusterTime from another session, ensuring subsequent operations in
this session are causally consistent with the last operation in the
other session
PARAMETERS
+ session: A mongoc_client_session_t.
+ cluster_time: The session's new cluster time, as a bson_t like
{"cluster time": <timestamp>}.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,C2025T_SESSION_ADVANCE_CLUSTER_TIME(3)
mongoc_client_session_advance_operation_time.3
MONGOC_CLIENT_SESSION_ADVANCE_OPERATIONoTIME(3)SSION_ADVANCE_OPERATION_TIME(3)
SYNOPSIS
void
mongoc_client_session_advance_operation_time (mongoc_client_session_t *session,
uint32_t timestamp,
uint32_t increment);
Advance the session's operation time, expressed as a BSON Timestamp
with timestamp and increment components. Has an effect only if the new
operation time is greater than the session's current operation time.
Use mongoc_client_session_advance_operation_time() and
mongoc_client_session_advance_cluster_time() to copy the operationTime
and clusterTime from another session, ensuring subsequent operations in
this session are causally consistent with the last operation in the
other session
PARAMETERS
+ session: A mongoc_client_session_t.
+ timestamp: The new operationTime's timestamp component.
+ increment: The new operationTime's increment component.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,I2025SESSION_ADVANCE_OPERATION_TIME(3)
mongoc_client_session_append.3
MONGOC_CLIENT_SESSION_APPEND(3) libmongoc MONGOC_CLIENT_SESSION_APPEND(3)
SYNOPSIS
bool
mongoc_client_session_append (const mongoc_client_session_t *client_session,
bson_t *opts,
bson_error_t *error);
PARAMETERS
+ client_session: A pointer to a mongoc_client_session_t.
+ opts: A pointer to a bson_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
This function appends a logical session id to command options. Use it
to configure a session for any function that takes an options document,
such as mongoc_client_write_command_with_opts().
It is an error to use a session for unacknowledged writes.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and fills out error.
EXAMPLE
See the example code for mongoc_client_session_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_SESSION_APPEND(3)
mongoc_client_session_commit_transaction.3
MONGOC_CLIENT_SESSION_COMMIT_TRANSACTION(3)cIENT_SESSION_COMMIT_TRANSACTION(3)
SYNOPSIS
bool
mongoc_client_session_commit_transaction (mongoc_client_session_t *session,
bson_t *reply,
bson_error_t *error);
Commit a multi-document transaction.
PARAMETERS
+ session: A mongoc_client_session_t.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
RETURN
Returns true if the transaction was committed. Returns false and sets
error if there are invalid arguments, such as a session with no trans-
action in progress, or if there is a server or network error.
If a reply is supplied, it is always initialized and must be freed with
bson_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025ENT_SESSION_COMMIT_TRANSACTION(3)
mongoc_client_session_destroy.3
MONGOC_CLIENT_SESSION_DESTROY(3) libmongoc MONGOC_CLIENT_SESSION_DESTROY(3)
SYNOPSIS
void
mongoc_client_session_destroy (mongoc_client_session_t *session);
End a session, returning its session id to the pool, and free all
client resources associated with the session. If a multi-document
transaction is in progress, abort it. Does nothing if session is NULL.
See the example code for mongoc_client_session_t.
PARAMETERS
+ session: A mongoc_client_session_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_SESSION_DESTROY(3)
mongoc_client_session_get_client.3
MONGOC_CLIENT_SESSION_GET_CLIENT(3)libmongocONGOC_CLIENT_SESSION_GET_CLIENT(3)
SYNOPSIS
mongoc_client_t *
mongoc_client_session_get_client (const mongoc_client_session_t *session);
Returns the mongoc_client_t from which this session was created. See
mongoc_client_start_session().
PARAMETERS
+ session: A mongoc_client_session_t.
RETURNS
A mongoc_client_t that should not be freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_CLIENT_SESSION_GET_CLIENT(3)
mongoc_client_session_get_cluster_time.3
MONGOC_CLIENT_SESSION_GET_CLUSTER_TIME(3)gocCLIENT_SESSION_GET_CLUSTER_TIME(3)
SYNOPSIS
const bson_t *
mongoc_client_session_get_cluster_time (const mongoc_client_session_t *session);
Get the session's clusterTime as a BSON document.
PARAMETERS
+ session: A mongoc_client_session_t.
RETURNS
If the session has not been used for any operation and
mongoc_client_session_advance_cluster_time() has not been called, a
bson_t that is valid only for the lifetime of session. Otherwise, NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025LIENT_SESSION_GET_CLUSTER_TIME(3)
mongoc_client_session_get_dirty.3
MONGOC_CLIENT_SESSION_GET_DIRTY(3) libmongocMONGOC_CLIENT_SESSION_GET_DIRTY(3)
SYNOPSIS
bool
mongoc_client_session_get_dirty (const mongoc_client_session_t *session);
Indicates whether session has been marked "dirty" as defined in the
driver sessions specification.
PARAMETERS
+ session: A const mongoc_client_session_t.
DESCRIPTION
This function is intended for use by drivers that wrap libmongoc. It is
not useful in client applications.
RETURNS
A boolean indicating whether the session has been marked "dirty".
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_CLIENT_SESSION_GET_DIRTY(3)
mongoc_client_session_get_lsid.3
MONGOC_CLIENT_SESSION_GET_LSID(3) libmongoc MONGOC_CLIENT_SESSION_GET_LSID(3)
SYNOPSIS
const bson_t *
mongoc_client_session_get_lsid (mongoc_client_session_t *session);
Get the server-side "logical session ID" associated with this
mongoc_client_session_t as a BSON document.
PARAMETERS
+ session: A mongoc_client_session_t.
RETURNS
A bson_t that is valid only for the lifetime of session.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_CLIENT_SESSION_GET_LSID(3)
mongoc_client_session_get_operation_time.3
MONGOC_CLIENT_SESSION_GET_OPERATIONlTIME(3)cIENT_SESSION_GET_OPERATION_TIME(3)
SYNOPSIS
void
mongoc_client_session_get_operation_time (const mongoc_client_session_t *session,
uint32_t *timestamp,
uint32_t *increment);
Get the session's operationTime, expressed as a BSON Timestamp with
timestamp and increment components. If the session has not been used
for any operations, the timestamp and increment are 0.
PARAMETERS
+ session: A mongoc_client_session_t.
+ timestamp: A pointer to a uint32_t to receive the timestamp compo-
nent.
+ increment: A pointer to a uint32_t to receive the increment compo-
nent.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025ENT_SESSION_GET_OPERATION_TIME(3)
mongoc_client_session_get_opts.3
MONGOC_CLIENT_SESSION_GET_OPTS(3) libmongoc MONGOC_CLIENT_SESSION_GET_OPTS(3)
SYNOPSIS
const mongoc_session_opt_t *
mongoc_client_session_get_opts (const mongoc_client_session_t *session);
Get a reference to the mongoc_session_opt_t with which this session was
configured.
PARAMETERS
+ session: A mongoc_client_session_t.
RETURNS
A mongoc_session_opt_t that is valid only for the lifetime of session.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_CLIENT_SESSION_GET_OPTS(3)
mongoc_client_session_get_server_id.3
MONGOC_CLIENT_SESSION_GET_SERVER_ID(3)mongocOC_CLIENT_SESSION_GET_SERVER_ID(3)
SYNOPSIS
uint32_t
mongoc_client_session_get_server_id (const mongoc_client_session_t *session);
Get the "server ID" of the mongos this mongoc_client_session_t is
pinned to.
PARAMETERS
+ session: A mongoc_client_session_t.
RETURNS
A server ID or 0 if this mongoc_client_session_t is not pinned.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_CLIENT_SESSION_GET_SERVER_ID(3)
mongoc_client_session_get_transaction_state.3
MONGOC_CLIENT_SESSION_GET_TRANSACTIONbSTATE(3)SESSION_GET_TRANSACTION_STATE(3)
SYNOPSIS
mongoc_transaction_state_t
mongoc_client_session_get_transaction_state (const mongoc_client_session_t *session);
Returns the current transaction state for this session.
PARAMETERS
+ session: A mongoc_client_session_t.
RETURN
Returns a mongoc_transaction_state_t that represents the current trans-
action state.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,L2025_SESSION_GET_TRANSACTION_STATE(3)
mongoc_client_session_in_transaction.3
MONGOC_CLIENT_SESSION_IN_TRANSACTION(3)ongocC_CLIENT_SESSION_IN_TRANSACTION(3)
SYNOPSIS
bool
mongoc_client_session_in_transaction (const mongoc_client_session_t *session);
Check whether a multi-document transaction is in progress for this ses-
sion.
PARAMETERS
+ session: A mongoc_client_session_t.
RETURN
Returns true if a transaction was started and has not been committed or
aborted, otherwise false.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_CLIENT_SESSION_IN_TRANSACTION(3)
mongoc_client_session_start_transaction.3
MONGOC_CLIENT_SESSION_START_TRANSACTION(3)ocLIENT_SESSION_START_TRANSACTION(3)
SYNOPSIS
bool
mongoc_client_session_start_transaction (mongoc_client_session_t *session,
const mongoc_transaction_opt_t *opts,
bson_error_t *error);
Start a multi-document transaction for all following operations in this
session. Any options provided in opts override options passed to
mongoc_session_opts_set_default_transaction_opts(), and options inher-
ited from the mongoc_client_t. The opts argument is copied and can be
freed after calling this function.
The transaction must be completed with
mongoc_client_session_commit_transaction() or
mongoc_client_session_abort_transaction(). An in-progress transaction
is automatically aborted by mongoc_client_session_destroy().
If a command inside of the transaction fails, it may cause the transac-
tion on the server to be aborted. An attempt to commit such transaction
will be rejected with NoSuchTransaction error.
PARAMETERS
+ session: A mongoc_client_session_t.
+ opts: A mongoc_transaction_opt_t or NULL.
+ error: An optional location for a bson_error_t or NULL.
RETURN
Returns true if the transaction was started. Returns false and sets er-
ror if there are invalid arguments, such as a session with a transac-
tion already in progress.
EXAMPLE
The following example demonstrates how to use error labels to reliably
execute a multi-document transaction despite network errors and other
transient failures.
example-transaction.c
/* gcc example-transaction.c -o example-transaction \
* $(pkg-config --cflags --libs libmongoc-1.0) */
/* ./example-transaction [CONNECTION_STRING] */
#include <stdio.h>
#include <mongoc/mongoc.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) {
MONGOC_ERROR ("failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
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 {
MONGOC_ERROR ("Failed to create collection: %s", 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) {
MONGOC_ERROR ("Failed to start session: %s", 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)) {
MONGOC_ERROR ("Could not add session to opts: %s", error.message);
goto done;
}
retry_transaction:
r = mongoc_client_session_start_transaction (session, txn_opts, &error);
if (!r) {
MONGOC_ERROR ("Failed to start transaction: %s", 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) {
MONGOC_ERROR ("Insert failed: %s", 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 {
MONGOC_ERROR ("Warning: commit failed: %s", 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;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025IENT_SESSION_START_TRANSACTION(3)
mongoc_client_session_t.3
MONGOC_CLIENT_SESSION_T(3) libmongoc MONGOC_CLIENT_SESSION_T(3)
Use a session for a sequence of operations, optionally with causal consis-
tency. See the MongoDB Manual Entry for Causal Consistency.
SYNOPSIS
Start a session with mongoc_client_start_session(), use the 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.
By default, sessions are causally consistent. To disable causal consis-
tency, 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 ses-
sion 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.
FORK SAFETY
A mongoc_client_session_t is only usable in the parent process after a
fork. The child process must call mongoc_client_reset() on the client
field.
EXAMPLE
example-session.c
/* gcc example-session.c -o example-session \
* $(pkg-config --cflags --libs libmongoc-1.0) */
/* ./example-session [CONNECTION_STRING] */
#include <stdio.h>
#include <mongoc/mongoc.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: %s\n"
"error message: %s\n",
uri_string,
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;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_SESSION_T(3)
mongoc_client_session_with_transaction.3
MONGOC_CLIENT_SESSION_WITH_TRANSACTION(3)gocCLIENT_SESSION_WITH_TRANSACTION(3)
SYNOPSIS
bool
mongoc_client_session_with_transaction (mongoc_client_session_t *session,
mongoc_client_session_with_transaction_cb_t cb,
const mongoc_transaction_opt_t *opts,
void *ctx,
bson_t *reply,
bson_error_t *error);
This method will start a new transaction on session, run cb, and then
commit the transaction. If it cannot commit the transaction, the entire
sequence may be retried, and cb may be run multiple times. ctx will be
passed to cb each time it is called.
This method has an internal time limit of 120 seconds, and will retry
until that time limit is reached. This timeout is not configurable.
cb should not attempt to start new transactions, but should simply run
operations meant to be contained within a transaction. The cb does not
need to commit transactions; this is handled by the
mongoc_client_session_with_transaction(). If cb does commit or abort a
transaction, however, this method will return without taking further
action.
If a command inside cb fails, it may cause the transaction on the
server to be aborted. This situation is normally handled transparently
by the driver. However, if the application does not return that error
from cb, the driver will not be able to determine whether the transac-
tion was aborted or not. The driver will then retry cb indefinitely. To
avoid this situation, the application MUST NOT silently handle errors
within cb. If the application needs to handle errors within cb, it MUST
return them after doing so.
The parameter reply is initialized even upon failure to simplify memory
management.
PARAMETERS
+ session: A mongoc_client_session_t.
+ cb: A mongoc_client_session_with_transaction_cb_t callback, which
will run inside of a new transaction on the session. See example be-
low.
+ opts: An optional mongoc_transaction_opt_t.
+ ctx: A void*. This user-provided data will be passed to cb.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
RETURN
Returns true if the transaction was completed successfully. Otherwise,
returns false in case of failure. In cases of failure error will also
be set, except if the passed-in cb fails without setting error. If a
non-NULL reply is passed in, reply will be set to the value of the last
server response, except if the passed-in cb fails without setting a re-
ply.
EXAMPLE
Use with_transaction() to run a callback within a transaction
/* gcc example-with-transaction-cb.c -o example-with-transaction-cb $(pkg-config
* --cflags --libs libmongoc-1.0) */
/* ./example-with-transaction-cb [CONNECTION_STRING] */
#include <mongoc/mongoc.h>
#include <stdio.h>
#include <stdlib.h>
/*
* We pass this context object to mongoc_client_session_with_transaction() along
* with our callback function. The context object will be passed to our callback
* function when it runs, so we can access it.
*/
typedef struct {
mongoc_collection_t *collection;
bson_t *insert_opts;
} ctx_t;
/*
* We pass this method as the callback to
* mongoc_client_session_with_transaction(). The insert that this method
* performs will happen inside of a new transaction.
*/
bool
create_and_insert_doc (mongoc_client_session_t *session,
void *ctx,
bson_t **reply, /* out param for our server reply */
bson_error_t *error)
{
/*
* mongoc_collection_insert_one requires an uninitialized, stack-allocated
* bson_t to receive the update result
*/
bson_t local_reply;
bson_t *doc = NULL;
ctx_t *data = NULL;
bool retval;
/*
* Create a new bson document - { id: 1 }
*/
doc = BCON_NEW ("_id", BCON_INT32 (1));
printf ("Running the user-defined callback in a newly created transaction...\n");
data = (ctx_t *) ctx;
retval = mongoc_collection_insert_one (data->collection, doc, data->insert_opts, &local_reply, error);
/*
* To return to the mongoc_client_session_with_transaction() method, set
* *reply to a new copy of our local_reply before destroying it.
*/
*reply = bson_copy (&local_reply);
bson_destroy (&local_reply);
bson_destroy (doc);
return retval;
}
int
main (int argc, char *argv[])
{
int exit_code = EXIT_FAILURE;
mongoc_uri_t *uri = NULL;
const char *uri_string = "mongodb://127.0.0.1/?appname=with-txn-cb-example";
mongoc_client_t *client = NULL;
mongoc_database_t *database = NULL;
mongoc_collection_t *collection = NULL;
mongoc_client_session_t *session = NULL;
bson_t *insert_opts = NULL;
bson_t reply;
ctx_t ctx;
char *str;
bson_error_t error;
/*
* Required to initialize libmongoc's internals
*/
mongoc_init ();
/*
* Optionally get MongoDB URI from command line
*/
if (argc > 1) {
uri_string = argv[1];
}
/*
* Safely create a MongoDB URI object from the given string
*/
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
MONGOC_ERROR ("failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
goto done;
}
/*
* Create a new client instance
*/
client = mongoc_client_new_from_uri (uri);
if (!client) {
goto done;
}
mongoc_client_set_error_api (client, 2);
/*
* Get a handle on the database "example-with-txn-cb"
*/
database = mongoc_client_get_database (client, "example-with-txn-cb");
/*
* 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 {
MONGOC_ERROR ("Failed to create collection: %s", error.message);
goto done;
}
}
/*
* Pass NULL for options - by default the session is causally consistent
*/
session = mongoc_client_start_session (client, NULL, &error);
if (!session) {
MONGOC_ERROR ("Failed to start session: %s", error.message);
goto done;
}
/*
* Append a logical session id to command options
*/
insert_opts = bson_new ();
if (!mongoc_client_session_append (session, insert_opts, &error)) {
MONGOC_ERROR ("Could not add session to opts: %s", error.message);
goto done;
}
ctx.collection = collection;
ctx.insert_opts = insert_opts;
/*
* This method will start a new transaction on session, run our callback
* function, i.e., &create_and_insert_doc, passing &ctx as an argument and
* commit the transaction.
*/
if (!mongoc_client_session_with_transaction (session, &create_and_insert_doc, NULL, &ctx, &reply, &error)) {
MONGOC_ERROR ("Insert failed: %s", error.message);
goto done;
}
str = bson_as_relaxed_extended_json (&reply, NULL);
printf ("%s\n", str);
exit_code = EXIT_SUCCESS;
done:
bson_free (str);
bson_destroy (&reply);
bson_destroy (insert_opts);
mongoc_client_session_destroy (session);
mongoc_collection_destroy (collection);
mongoc_database_destroy (database);
mongoc_client_destroy (client);
mongoc_uri_destroy (uri);
mongoc_cleanup ();
return exit_code;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025LIENT_SESSION_WITH_TRANSACTION(3)
mongoc_client_session_with_transaction_cb_t.3
MONGOC_CLIENT_SESSION_WITH_TRANSACTIONmCBgT(3)SESSION_WITH_TRANSACTION_CB_T(3)
SYNOPSIS
typedef bool (*mongoc_client_session_with_transaction_cb_t) (
mongoc_client_session_t *session,
void *ctx,
bson_t **reply,
bson_error_t *error);
Provide this callback to mongoc_client_session_with_transaction(). The
callback should run a sequence of operations meant to be contained
within a transaction. The callback should not attempt to start or com-
mit transactions.
PARAMETERS
+ session: A mongoc_client_session_t.
+ ctx: A void* set to the the user-provided ctx passed to
mongoc_client_session_with_transaction().
+ 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.
SEE ALSO:
mongoc_client_session_with_transaction()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,L2025_SESSION_WITH_TRANSACTION_CB_T(3)
mongoc_client_set_apm_callbacks.3
MONGOC_CLIENT_SET_APM_CALLBACKS(3) libmongocMONGOC_CLIENT_SET_APM_CALLBACKS(3)
SYNOPSIS
bool
mongoc_client_set_apm_callbacks (mongoc_client_t *client,
mongoc_apm_callbacks_t *callbacks,
void *context);
Register a set of callbacks to receive Application Performance Monitor-
ing events.
The callbacks are copied by the client and may be safely destroyed by
the caller after this API call completes. If a context is passed, it is
the application's responsibility to ensure context remains valid for
the lifetime of the client.
PARAMETERS
+ client: A mongoc_client_t.
+ callbacks: Optional mongoc_apm_callbacks_t. Pass NULL to clear all
callbacks.
+ context: Optional pointer to include with each event notification.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and logs an error.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_CLIENT_SET_APM_CALLBACKS(3)
mongoc_client_set_appname.3
MONGOC_CLIENT_SET_APPNAME(3) libmongoc MONGOC_CLIENT_SET_APPNAME(3)
SYNOPSIS
bool
mongoc_client_set_appname (mongoc_client_t *client, const char *appname)
Sets the application name for this client. This string, along with
other internal driver details, is sent to the server as part of the
initial connection handshake ("hello").
appname is copied, and doesn't have to remain valid after the call to
mongoc_client_set_appname().
This function will log an error and return false in the following
cases:
+ appname is longer than MONGOC_HANDSHAKE_APPNAME_MAX
+ client has already initiated a handshake
+ client is from a mongoc_client_pool_t
PARAMETERS
+ client: A mongoc_client_t.
+ appname: The application name, of length at most MONGOC_HAND-
SHAKE_APPNAME_MAX.
RETURNS
true if the appname is set successfully. Otherwise, false.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_SET_APPNAME(3)
mongoc_client_set_error_api.3
MONGOC_CLIENT_SET_ERROR_API(3) libmongoc MONGOC_CLIENT_SET_ERROR_API(3)
SYNOPSIS
bool
mongoc_client_set_error_api (mongoc_client_t *client, int32_t version);
Configure how the C Driver reports errors. See Setting the Error API
Version.
Do not use this function with pooled clients, see
mongoc_client_pool_set_error_api().
PARAMETERS
+ client: A mongoc_client_t.
+ version: The version of the error API, either MONGOC_ERROR_API_VER-
SION_LEGACY or MONGOC_ERROR_API_VERSION_2.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and logs an error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_SET_ERROR_API(3)
mongoc_client_set_read_concern.3
MONGOC_CLIENT_SET_READ_CONCERN(3) libmongoc MONGOC_CLIENT_SET_READ_CONCERN(3)
SYNOPSIS
void
mongoc_client_set_read_concern (mongoc_client_t *client,
const mongoc_read_concern_t *read_concern);
Sets the read concern for the client. This only affects future opera-
tions, collections, and databases inheriting from client.
The default read concern is MONGOC_READ_CONCERN_LEVEL_LOCAL. This is
the correct read concern for the great majority of applications.
It is a programming error to call this function on a client from a
mongoc_client_pool_t. For pooled clients, set the read concern with the
MongoDB URI instead.
PARAMETERS
+ client: A mongoc_client_t.
+ read_concern: A mongoc_read_concern_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_CLIENT_SET_READ_CONCERN(3)
mongoc_client_set_read_prefs.3
MONGOC_CLIENT_SET_READ_PREFS(3) libmongoc MONGOC_CLIENT_SET_READ_PREFS(3)
SYNOPSIS
void
mongoc_client_set_read_prefs (mongoc_client_t *client,
const mongoc_read_prefs_t *read_prefs);
Sets the default read preferences to use with future operations upon
client.
The global default is to read from the replica set primary.
It is a programming error to call this function on a client from a
mongoc_client_pool_t. For pooled clients, set the read preferences with
the MongoDB URI instead.
Please see the MongoDB website for a description of Read Preferences.
PARAMETERS
+ client: A mongoc_client_t.
+ read_prefs: A mongoc_read_prefs_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_SET_READ_PREFS(3)
mongoc_client_set_server_api.3
MONGOC_CLIENT_SET_SERVER_API(3) libmongoc MONGOC_CLIENT_SET_SERVER_API(3)
SYNOPSIS
bool
mongoc_client_set_server_api (mongoc_client_t *client,
const mongoc_server_api_t *api,
bson_error_t *error);
Set the API version to use for client. Once the API version is set on a
client, it may not be changed to a new value. Attempting to do so will
cause this method to fail and set error.
PARAMETERS
+ client: A mongoc_client_t.
+ api: A mongoc_server_api_t.
+ error: A bson_error_t.
RETURNS
True if the version was successfully set, false if not. On failure, er-
ror will be set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_SET_SERVER_API(3)
mongoc_client_set_sockettimeoutms.3
MONGOC_CLIENT_SET_SOCKETTIMEOUTMS(3)ibmongocNGOC_CLIENT_SET_SOCKETTIMEOUTMS(3)
SYNOPSIS
void
mongoc_client_set_sockettimeoutms (mongoc_client_t *client, int32_t timeoutms);
Change the sockettimeoutms of the mongoc_client_t.
If client was obtained from a mongoc_client_pool_t, the socket timeout
is restored to the previous value when calling
mongoc_client_pool_push().
PARAMETERS
+ client: A mongoc_client_t.
+ timeoutms: The requested timeout value in milliseconds.
SEE ALSO:
URI Connection Options
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_CLIENT_SET_SOCKETTIMEOUTMS(3)
mongoc_client_set_ssl_opts.3
MONGOC_CLIENT_SET_SSL_OPTS(3) libmongoc MONGOC_CLIENT_SET_SSL_OPTS(3)
SYNOPSIS
#ifdef MONGOC_ENABLE_SSL
void
mongoc_client_set_ssl_opts (mongoc_client_t *client,
const mongoc_ssl_opt_t *opts);
#endif
NOTE:
Though some API names include the term "ssl", the C driver only sup-
port TLS protocols, which supersede SSL.
Sets the TLS (SSL) options to use when connecting to TLS enabled Mon-
goDB servers.
The mongoc_ssl_opt_t struct is copied by the client along with the
strings it points to (pem_file, pem_pwd, ca_file, ca_dir, and crl_file)
so they don't have to remain valid after the call to
mongoc_client_set_ssl_opts().
A call to mongoc_client_set_ssl_opts() overrides all TLS options set
through the connection string with which the mongoc_client_t was con-
structed.
It is a programming error to call this function on a client from a
mongoc_client_pool_t. Instead, call mongoc_client_pool_set_ssl_opts()
on the pool before popping any clients.
Changed in version 2.0.0: This function logs an error and immediately
returns if client is from a mongoc_client_pool_t. Previously this func-
tion unsafely applied the options to the pooled client.
PARAMETERS
+ client: A mongoc_client_t.
+ opts: A mongoc_ssl_opt_t.
AVAILABILITY
This feature requires that the MongoDB C driver was compiled with -DEN-
ABLE_SSL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_SET_SSL_OPTS(3)
mongoc_client_set_stream_initiator.3
MONGOC_CLIENT_SET_STREAM_INITIATOR(3)bmongocGOC_CLIENT_SET_STREAM_INITIATOR(3)
SYNOPSIS
void
mongoc_client_set_stream_initiator (mongoc_client_t *client,
mongoc_stream_initiator_t initiator,
void *user_data);
The mongoc_client_set_stream_initiator() function shall associate a
given mongoc_client_t with a new stream initiator. This will completely
replace the default transport (buffered TCP, possibly with TLS). The
initiator should fulfill the mongoc_stream_t contract. user_data is
passed through to the initiator callback and may be used for whatever
run time customization is necessary.
It is a programming error to call this function on a mongoc_client_t
from a mongoc_client_pool_t.
Changed in version 2.0.0: This function logs an error and immediately
returns if client is from a mongoc_client_pool_t. Previously this func-
tion unsafely applied the initiator to the pooled client.
If user_data is passed, it is the application's responsibility to en-
sure user_data remains valid for the lifetime of the client.
PARAMETERS
+ client: A mongoc_client_t.
+ initiator: A mongoc_stream_initiator_t.
+ user_data: User supplied pointer for callback function.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_CLIENT_SET_STREAM_INITIATOR(3)
mongoc_client_set_structured_log_opts.3
MONGOC_CLIENT_SET_STRUCTURED_LOG_OPTS(3)ngoc_CLIENT_SET_STRUCTURED_LOG_OPTS(3)
SYNOPSIS
bool
mongoc_client_set_structured_log_opts (mongoc_client_t *client,
const mongoc_structured_log_opts_t *opts);
Reconfigures this client's structured logging subsystem. See Structured
Logging.
This function must not be called on clients that are part of a
mongoc_client_pool_t. Structured logging for pools must be configured
with mongoc_client_pool_set_structured_log_opts() before the first call
to mongoc_client_pool_pop().
The mongoc_structured_log_opts_t is copied by the client and may be
safely destroyed by the caller after this API call completes. The ap-
plication is responsible for ensuring any user_data referenced by opts
remains valid for the lifetime of the client.
By default, the mongoc_client_t will have log options captured from the
environment during mongoc_client_new(). See
mongoc_structured_log_opts_new() for a list of the supported options.
The structured logging subsystem may be disabled by passing NULL as
opts or equivalently by passing NULL as the
mongoc_structured_log_func_t in
mongoc_structured_log_opts_set_handler().
PARAMETERS
+ client: A mongoc_client_t.
+ opts: A mongoc_structured_log_opts_t allocated with
mongoc_structured_log_opts_new(), or NULL to disable structured log-
ging.
RETURNS
Returns true when used correctly. If called on a pooled client, returns
false and logs a warning.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025CLIENT_SET_STRUCTURED_LOG_OPTS(3)
mongoc_client_set_write_concern.3
MONGOC_CLIENT_SET_WRITE_CONCERN(3) libmongocMONGOC_CLIENT_SET_WRITE_CONCERN(3)
SYNOPSIS
void
mongoc_client_set_write_concern (mongoc_client_t *client,
const mongoc_write_concern_t *write_concern);
Sets the write concern for the client. This only affects future opera-
tions, collections, and databases inheriting from client.
The default write concern is MONGOC_WRITE_CONCERN_W_DEFAULT: the driver
blocks awaiting basic acknowledgement of write operations from MongoDB.
This is the correct write concern for the great majority of applica-
tions.
It is a programming error to call this function on a client from a
mongoc_client_pool_t. For pooled clients, set the write concern with
the MongoDB URI instead.
PARAMETERS
+ client: A mongoc_client_t.
+ write_concern: A mongoc_write_concern_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_CLIENT_SET_WRITE_CONCERN(3)
mongoc_client_start_session.3
MONGOC_CLIENT_START_SESSION(3) libmongoc MONGOC_CLIENT_START_SESSION(3)
SYNOPSIS
mongoc_client_session_t *
mongoc_client_start_session (mongoc_client_t *client,
mongoc_session_opt_t *opts,
bson_error_t *error)
Create a session for a sequence of operations.
Start a session with mongoc_client_start_session(), use the 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.
By default, sessions are causally consistent. To disable causal consis-
tency, 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 ses-
sion 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.
PARAMETERS
+ client: A mongoc_client_t.
+ opts: An optional mongoc_session_opt_t.
+ error: A bson_error_t.
RETURNS
If successful, this function returns a newly allocated
mongoc_client_session_t that should be freed with
mongoc_client_session_destroy() when no longer in use. On error, re-
turns NULL and sets error.
ERRORS
This function can fail if the driver is not built with crypto support,
if opts is misconfigured, or if the session is configured with options
that the server does not support.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_START_SESSION(3)
mongoc_client_t.3
MONGOC_CLIENT_T(3) libmongoc MONGOC_CLIENT_T(3)
A single-threaded MongoDB connection. See Connection Pooling.
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
server, replica set, or sharded cluster. It maintains management of un-
derlying 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 cus-
tom 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 recom-
mended that you use the thread-safe mongoc_client_pool_t to retrieve a
mongoc_client_t for your thread.
FORK SAFETY
A mongoc_client_t is only usable in the parent process after a fork.
The child process must call mongoc_client_reset().
EXAMPLE
example-client.c
/* 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: %s\n"
"error message: %s\n",
uri_string,
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;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_T(3)
mongoc_client_watch.3
MONGOC_CLIENT_WATCH(3) libmongoc MONGOC_CLIENT_WATCH(3)
SYNOPSIS
mongoc_change_stream_t*
mongoc_client_watch (mongoc_client_t *client,
const bson_t *pipeline,
const bson_t *opts);
A helper function to create a change stream. It is preferred to call
this function over using a raw aggregation to create a change stream.
This function uses the read preference and read concern of the client.
If the change stream needs to re-establish connection, the same read
preference will be used. This may happen if the change stream encoun-
ters a resumable error.
WARNING:
A change stream is only supported with majority read concern.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
PARAMETERS
+ db: A mongoc_client_t specifying the client which the change stream
listens to.
+ pipeline: A bson_t representing an aggregation pipeline appended to
the change stream. This may be an empty document.
+ opts: A bson_t containing change stream options.
Changed in version 2.0.0: batchSize of 0 is applied to the aggregate
command. 0 was previously ignored.
opts may be NULL or a BSON document with additional command options:
+ batchSize: An int32 requesting a limit of documents returned in each
server reply. If positive, the batchSize is applied to both aggregate
and getMore commands. If 0, the batchSize is only applied to the ag-
gregate command (Useful to request an immediate cursor without sig-
nificant server-side work. See Aggregate Data Specifying Batch Size).
If omitted or negative, the value is ignored and server defaults are
used (See Cursor Batches for a description of server defaults).
+ resumeAfter: A Document representing the logical starting point of
the change stream. The result of
mongoc_change_stream_get_resume_token() or the _id field of any
change received from a change stream can be used here. This option is
mutually exclusive with startAfter and startAtOperationTime.
+ startAfter: A Document representing the logical starting point of the
change stream. Unlike resumeAfter, this can resume notifications af-
ter an "invalidate" event. The result of
mongoc_change_stream_get_resume_token() or the _id field of any
change received from a change stream can be used here. This option
is mutually exclusive with resumeAfter and startAtOperationTime.
+ startAtOperationTime: A Timestamp. The change stream only provides
changes that occurred at or after the specified timestamp. Any com-
mand run against the server will return an operation time that can be
used here. This option is mutually exclusive with resumeAfter and
startAfter.
+ maxAwaitTimeMS: An int64 representing the maximum amount of time a
call to mongoc_change_stream_next() will block waiting for data
+ fullDocument: An optional UTF-8 string. Set this option to "default",
"updateLookup", "whenAvailable", or "required", If unset, The string
"default" is assumed. Set this option to "updateLookup" to direct the
change stream cursor to lookup the most current majority-committed
version of the document associated to an update change stream event.
+ fullDocumentBeforeChange: An optional UTF-8 string. Set this option
to "whenAvailable", "required", or "off". When unset, the default
value is "off". Similar to "fullDocument", but returns the value of
the document before the associated change.
+ showExpandedEvents: Set to true to return an expanded list of change
stream events. Available only on MongoDB versions >=6.0
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Only string values are supported prior to MongoDB
4.4.
RETURNS
A newly allocated mongoc_change_stream_t which must be freed with
mongoc_change_stream_destroy() when no longer in use. The returned
mongoc_change_stream_t is never NULL. If there is an error, it can be
retrieved with mongoc_change_stream_error_document(), and subsequent
calls to mongoc_change_stream_next() will return false.
SEE ALSO:
mongoc_database_watch()
mongoc_collection_watch()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CLIENT_WATCH(3)
mongoc_client_write_command_with_opts.3
MONGOC_CLIENT_WRITE_COMMAND_WITH_OPTS(3)ngoc_CLIENT_WRITE_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_client_write_command_with_opts (mongoc_client_t *client,
const char *db_name,
const bson_t *command,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, applying logic that is specific to
commands that write, and taking the MongoDB server version into ac-
count. To send a raw command to the server without any of this logic,
use mongoc_client_command_simple().
Use this function for commands that write such as "drop" or "create-
Role" (but not for "insert", "update", or "delete", see Basic Write Op-
erations). Write concern and collation can be overridden by various
sources. In a transaction, read concern and write concern are prohib-
ited in opts. The highest-priority sources for these options are listed
first in the following table. The write concern is omitted for MongoDB
before 3.4.
+--------------+-----------+
|Write Concern | Collation |
+--------------+-----------+
|opts | opts |
+--------------+-----------+
|Transaction | |
+--------------+-----------+
|client | |
+--------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
reply is always initialized, and must be freed with bson_destroy().
PARAMETERS
+ client: A mongoc_client_t.
+ db_name: The name of the database to run the command on.
+ command: A bson_t containing the command specification.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
client, and use mongoc_client_session_append() to add the session to
opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
BASIC WRITE OPERATIONS
Do not use this function to call the basic write commands "insert",
"update", and "delete". Those commands require special logic not imple-
mented in mongoc_client_write_command_with_opts. For basic write opera-
tions use CRUD functions such as mongoc_collection_insert_one() and the
others described in the CRUD tutorial, or use the Bulk API.
EXAMPLE
example-command-with-opts.c
/*
Demonstrates how to prepare options for mongoc_client_read_command_with_opts and
mongoc_client_write_command_with_opts. First it calls "cloneCollectionAsCapped"
command with "writeConcern" option, then "distinct" command with "collation" and
"readConcern" options,
Start a MongoDB 3.4 replica set with --enableMajorityReadConcern and insert two
documents:
$ mongo
MongoDB Enterprise replset:PRIMARY> db.my_collection.insert({x: 1, y: "One"})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise replset:PRIMARY> db.my_collection.insert({x: 2, y: "Two"})
WriteResult({ "nInserted" : 1 })
Build and run the example:
gcc example-command-with-opts.c -o example-command-with-opts $(pkg-config
--cflags --libs libmongoc-1.0)
./example-command-with-opts [CONNECTION_STRING]
cloneCollectionAsCapped: { "ok" : 1 }
distinct: { "values" : [ 1, 2 ], "ok" : 1 }
*/
#include <mongoc/mongoc.h>
#include <stdio.h>
#include <stdlib.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
const char *uri_string = "mongodb://127.0.0.1/?appname=client-example";
mongoc_uri_t *uri;
bson_t *cmd;
bson_t *opts;
mongoc_write_concern_t *write_concern;
mongoc_read_prefs_t *read_prefs;
mongoc_read_concern_t *read_concern;
bson_t reply;
bson_error_t error;
char *json;
mongoc_init ();
if (argc > 1) {
uri_string = argv[1];
}
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
client = mongoc_client_new_from_uri (uri);
if (!client) {
return EXIT_FAILURE;
}
mongoc_client_set_error_api (client, 2);
cmd = BCON_NEW ("cloneCollectionAsCapped",
BCON_UTF8 ("my_collection"),
"toCollection",
BCON_UTF8 ("my_capped_collection"),
"size",
BCON_INT64 (1024 * 1024));
/* include write concern "majority" in command options */
write_concern = mongoc_write_concern_new ();
mongoc_write_concern_set_wmajority (write_concern, 10000 /* wtimeoutMS */);
opts = bson_new ();
mongoc_write_concern_append (write_concern, opts);
if (mongoc_client_write_command_with_opts (client, "test", cmd, opts, &reply, &error)) {
json = bson_as_canonical_extended_json (&reply, NULL);
printf ("cloneCollectionAsCapped: %s\n", json);
bson_free (json);
} else {
fprintf (stderr, "cloneCollectionAsCapped: %s\n", error.message);
}
bson_free (cmd);
bson_free (opts);
/* distinct values of "x" in "my_collection" where "y" sorts after "one" */
cmd = BCON_NEW ("distinct",
BCON_UTF8 ("my_collection"),
"key",
BCON_UTF8 ("x"),
"query",
"{",
"y",
"{",
"$gt",
BCON_UTF8 ("one"),
"}",
"}");
read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
/* "One" normally sorts before "one"; make "One" sort after "one" */
opts = BCON_NEW ("collation", "{", "locale", BCON_UTF8 ("en_US"), "caseFirst", BCON_UTF8 ("lower"), "}");
/* add a read concern to "opts" */
read_concern = mongoc_read_concern_new ();
mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_MAJORITY);
mongoc_read_concern_append (read_concern, opts);
if (mongoc_client_read_command_with_opts (client, "test", cmd, read_prefs, opts, &reply, &error)) {
json = bson_as_canonical_extended_json (&reply, NULL);
printf ("distinct: %s\n", json);
bson_free (json);
} else {
fprintf (stderr, "distinct: %s\n", error.message);
}
bson_destroy (cmd);
bson_destroy (opts);
bson_destroy (&reply);
mongoc_read_prefs_destroy (read_prefs);
mongoc_read_concern_destroy (read_concern);
mongoc_write_concern_destroy (write_concern);
mongoc_uri_destroy (uri);
mongoc_client_destroy (client);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025CLIENT_WRITE_COMMAND_WITH_OPTS(3)
mongoc_collection_aggregate.3
MONGOC_COLLECTION_AGGREGATE(3) libmongoc MONGOC_COLLECTION_AGGREGATE(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_collection_aggregate (mongoc_collection_t *collection,
mongoc_query_flags_t flags,
const bson_t *pipeline,
const bson_t *opts,
const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ collection: A mongoc_collection_t.
+ flags: A mongoc_query_flags_t. Not all flag values apply. In particu-
lar, setting MONGOC_QUERY_EXHAUST results in an error.
+ pipeline: A bson_t, either a BSON array or a BSON document containing
an array field named "pipeline".
+ opts: A bson_t containing options for the command, or NULL.
+ read_prefs: A mongoc_read_prefs_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ bypassDocumentValidation: Set to true to skip server-side schema val-
idation of the provided BSON documents.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
+ batchSize: An int32 representing number of documents requested to be
returned on each call to mongoc_cursor_next()
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Only string values are supported prior to MongoDB
4.4.
+ hint: A document or string that specifies the index to use to support
the query predicate.
For a list of all options, see the MongoDB Manual entry on the aggre-
gate command.
This function is considered a retryable read operation unless the pipe-
line contains a write stage like $out or $merge. Upon a transient er-
ror (a network error, errors due to replica set failover, etc.) the op-
eration is safely retried once. If retryreads is false in the URI (see
mongoc_uri_t) the retry behavior does not apply.
DESCRIPTION
This function creates a cursor which sends the aggregate command on the
underlying collection upon the first call to mongoc_cursor_next(). For
more information on building aggregation pipelines, see the MongoDB
Manual entry on the aggregate command.
Read preferences, read and write concern, and collation can be overrid-
den by various sources. The highest-priority sources for these options
are listed first in the following table. In a transaction, read concern
and write concern are prohibited in opts and the read preference must
be primary or NULL. Write concern is applied from opts, or if opts has
no write concern and the aggregation pipeline includes "$out", the
write concern is applied from collection. The write concern is omitted
for MongoDB before 3.4.
+-----------------+--------------+---------------+-----------+
|Read Preferences | Read Concern | Write Concern | Collation |
+-----------------+--------------+---------------+-----------+
|read_prefs | opts | opts | opts |
+-----------------+--------------+---------------+-----------+
|Transaction | Transaction | Transaction | |
+-----------------+--------------+---------------+-----------+
|collection | collection | collection | |
+-----------------+--------------+---------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
RETURNS
This function returns a newly allocated mongoc_cursor_t that should be
freed with mongoc_cursor_destroy() when no longer in use. The returned
mongoc_cursor_t is never NULL, even on error. The user must call
mongoc_cursor_next() on the returned mongoc_cursor_t to execute the
initial command.
Cursor errors can be checked with mongoc_cursor_error_document(). It
always fills out the bson_error_t if an error occurred, and optionally
includes a server reply document if the error occurred server-side.
WARNING:
Failure to handle the result of this function is a programming er-
ror.
EXAMPLE
#include <bson/bson.h>
#include <mongoc/mongoc.h>
static mongoc_cursor_t *
pipeline_query (mongoc_collection_t *collection)
{
mongoc_cursor_t *cursor;
bson_t *pipeline;
pipeline = BCON_NEW ("pipeline",
"[",
"{",
"$match",
"{",
"foo",
BCON_UTF8 ("A"),
"}",
"}",
"{",
"$match",
"{",
"bar",
BCON_BOOL (false),
"}",
"}",
"]");
cursor = mongoc_collection_aggregate (
collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL);
bson_destroy (pipeline);
return cursor;
}
OTHER PARAMETERS
When using $out, the pipeline stage that writes, the write_concern
field of the mongoc_cursor_t will be set to the mongoc_write_concern_t
parameter, if it is valid, and applied to the write command when
mongoc_cursor_next() is called. Pass any other parameters to the aggre-
gate command, besides pipeline, as fields in opts:
mongoc_write_concern_t *write_concern = mongoc_write_concern_new ();
mongoc_write_concern_set_w (write_concern, 3);
pipeline =
BCON_NEW ("pipeline", "[", "{", "$out", BCON_UTF8 ("collection2"), "}", "]");
opts = BCON_NEW ("bypassDocumentValidation", BCON_BOOL (true));
mongoc_write_concern_append (write_concern, opts);
cursor = mongoc_collection_aggregate (
collection1, MONGOC_QUERY_NONE, pipeline, opts, NULL);
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_AGGREGATE(3)
mongoc_collection_command_simple.3
MONGOC_COLLECTION_COMMAND_SIMPLE(3)libmongocONGOC_COLLECTION_COMMAND_SIMPLE(3)
SYNOPSIS
bool
mongoc_collection_command_simple (mongoc_collection_t *collection,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ command: A bson_t containing the command to execute.
+ read_prefs: An optional mongoc_read_prefs_t. Otherwise, the command
uses mode MONGOC_READ_PRIMARY.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
The collection's read preference, read concern, and write concern are
not applied to the command. The parameter reply is initialized even
upon failure to simplify memory management.
This function tries to unwrap an embedded error in the command when
possible. The unwrapped error will be propagated via the error parame-
ter. Additionally, the result document is set in reply.
This function is not considered a retryable read operation.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
This function does not check the server response for a write concern
error or write concern timeout.
EXAMPLE
The following is an example of executing the ping command.
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
static void
do_ping (mongoc_collection_t *collection)
{
bson_error_t error;
bson_t *cmd;
bson_t reply;
char *str;
cmd = BCON_NEW ("ping", BCON_INT32 (1));
if (mongoc_collection_command_simple (collection, cmd, NULL, &reply, &error)) {
str = bson_as_canonical_extended_json (&reply, NULL);
printf ("Got reply: %s\n", str);
bson_free (str);
} else {
fprintf (stderr, "Got error: %s\n", error.message);
}
bson_destroy (&reply);
bson_destroy (cmd);
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_COLLECTION_COMMAND_SIMPLE(3)
mongoc_collection_command_with_opts.3
MONGOC_COLLECTION_COMMAND_WITH_OPTS(3)mongocOC_COLLECTION_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_collection_command_with_opts (
mongoc_collection_t *collection,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, interpreting opts according to the
MongoDB server version. To send a raw command to the server without any
of this logic, use mongoc_client_command_simple().
Read preferences, read and write concern, and collation can be overrid-
den by various sources. The highest-priority sources for these options
are listed first:
+-----------------+--------------+---------------+-----------+
|Read Preferences | Read Concern | Write Concern | Collation |
+-----------------+--------------+---------------+-----------+
|read_prefs | opts | opts | opts |
+-----------------+--------------+---------------+-----------+
|Transaction | Transaction | Transaction | |
+-----------------+--------------+---------------+-----------+
In a transaction, read concern and write concern are prohibited in opts
and the read preference must be primary or NULL. See the example for
transactions and for the "distinct" command with opts.
reply is always initialized, and must be freed with bson_destroy().
PARAMETERS
+ collection: A mongoc_collection_t.
+ command: A bson_t containing the command specification.
+ read_prefs: An optional mongoc_read_prefs_t.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
This function is not considered a retryable read operation.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
The reply is not parsed for a write concern timeout or write concern
error.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_COLLECTION_COMMAND_WITH_OPTS(3)
mongoc_collection_copy.3
MONGOC_COLLECTION_COPY(3) libmongoc MONGOC_COLLECTION_COPY(3)
SYNOPSIS
mongoc_collection_t *
mongoc_collection_copy (mongoc_collection_t *collection);
PARAMETERS
+ collection: A mongoc_collection_t.
DESCRIPTION
Performs a deep copy of the collection struct and its configuration.
Useful if you intend to call mongoc_collection_set_write_concern(),
mongoc_collection_set_read_prefs(), or
mongoc_collection_set_read_concern(), and want to preserve an unaltered
copy of the struct.
This function does not copy the contents of the collection on the Mon-
goDB server.
RETURNS
A newly allocated mongoc_collection_t that should be freed with
mongoc_collection_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_COPY(3)
mongoc_collection_count_documents.3
MONGOC_COLLECTION_COUNT_DOCUMENTS(3)ibmongocNGOC_COLLECTION_COUNT_DOCUMENTS(3)
SYNOPSIS
int64_t
mongoc_collection_count_documents (mongoc_collection_t *collection,
const bson_t *filter,
const bson_t *opts,
const mongoc_read_prefs_t *read_prefs,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ filter: A bson_t containing the filter.
+ opts: A bson_t, NULL to ignore.
+ read_prefs: A mongoc_read_prefs_t or NULL.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
+ skip: An int specifying how many documents matching the query should
be skipped before counting.
+ limit: An int specifying the maximum number of documents to count.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Only string values are supported prior to MongoDB
4.4.
+ hint: A document or string that specifies the index to use to support
the query predicate.
Other options are included in the sent aggregate command. For a list of
all options, see the MongoDB Manual entry on the aggregate command.
DESCRIPTION
This functions executes a count query on collection. In contrast with
mongoc_collection_estimated_document_count(), the count returned is
guaranteed to be accurate.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
ERRORS
Errors are propagated via the error parameter.
RETURNS
-1 on failure, otherwise the number of documents counted.
EXAMPLE
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
static void
print_count (mongoc_collection_t *collection, bson_t *filter)
{
bson_error_t error;
int64_t count;
bson_t* opts = BCON_NEW ("skip", BCON_INT64(5));
count = mongoc_collection_count_documents (
collection, filter, opts, NULL, NULL, &error);
bson_destroy (opts);
if (count < 0) {
fprintf (stderr, "Count failed: %s\n", error.message);
} else {
printf ("%" PRId64 " documents counted.\n", count);
}
}
SEE ALSO:
mongoc_collection_estimated_document_count()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_COLLECTION_COUNT_DOCUMENTS(3)
mongoc_collection_create_bulk_operation_with_opts.3
MONGOC_COLLECTION_CREATE_BULKGOPERATIONoWITHCOPTS(3)ULK_OPERATION_WITH_OPTS(3)
SYNOPSIS
mongoc_bulk_operation_t *
mongoc_collection_create_bulk_operation_with_opts (
mongoc_collection_t *collection,
const bson_t *opts);
PARAMETERS
+ collection: A mongoc_collection_t.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ ordered: set to false to attempt to insert all documents, continuing
after errors.
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
DESCRIPTION
This function shall begin a new bulk operation. After creating this you
may call various functions such as mongoc_bulk_operation_update(),
mongoc_bulk_operation_insert() and others.
After calling mongoc_bulk_operation_execute() the commands will be exe-
cuted in as large as batches as reasonable by the client.
ERRORS
Errors are propagated when executing the bulk operation.
RETURNS
A newly allocated mongoc_bulk_operation_t that should be freed with
mongoc_bulk_operation_destroy() when no longer in use.
WARNING:
Failure to handle the result of this function is a programming er-
ror.
SEE ALSO:
Bulk Write Operations
mongoc_bulk_operation_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_MayL12,I2025REATE_BULK_OPERATION_WITH_OPTS(3)
mongoc_collection_create_indexes_with_opts.3
MONGOC_COLLECTION_CREATE_INDEXES_WITHbOPTS(3)CTION_CREATE_INDEXES_WITH_OPTS(3)
SYNOPSIS
typedef struct _mongoc_index_model_t mongoc_index_model_t;
mongoc_index_model_t *
mongoc_index_model_new (const bson_t *keys, const bson_t *opts);
void mongoc_index_model_destroy (mongoc_index_model_t *model);
bool
mongoc_collection_create_indexes_with_opts (mongoc_collection_t *collection,
mongoc_index_model_t **models,
size_t n_models,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ models: An array of mongoc_index_model_t *.
+ n_models: The number of models.
+ opts: Optional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Additional options passed in opts are appended to the createIndexes
command. See the MongoDB Manual for createIndexes for all supported op-
tions.
If no write concern is provided in opts, the collection's write concern
is used.
mongoc_index_model_t
Each mongoc_index_model_t represents an index to create. mongoc_in-
dex_model_new includes:
+ keys Expected to match the form of the key field in the createIndexes
command.
+ opts Optional index options appended as a sibling to the key field in
the createIndexes command.
DESCRIPTION
This function wraps around the createIndexes command.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
SEE ALSO:
Manage Collection Indexes.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,C2025CTION_CREATE_INDEXES_WITH_OPTS(3)
mongoc_collection_delete_many.3
MONGOC_COLLECTION_DELETE_MANY(3) libmongoc MONGOC_COLLECTION_DELETE_MANY(3)
SYNOPSIS
bool
mongoc_collection_delete_many (mongoc_collection_t *collection,
const bson_t *selector,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ selector: A bson_t containing the query to match documents.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
DESCRIPTION
This function removes all documents in the given collection that match
selector.
To delete at most one matching document, use
mongoc_collection_delete_one().
If you pass a non-NULL reply, it is filled out with the field "deleted-
Count". If there is a server error then reply contains either a
"writeErrors" array with one subdocument or a "writeConcernErrors" ar-
ray. The reply must be freed with bson_destroy().
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_DELETE_MANY(3)
mongoc_collection_delete_one.3
MONGOC_COLLECTION_DELETE_ONE(3) libmongoc MONGOC_COLLECTION_DELETE_ONE(3)
SYNOPSIS
bool
mongoc_collection_delete_one (mongoc_collection_t *collection,
const bson_t *selector,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ selector: A bson_t containing the query to match documents.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
DESCRIPTION
This function removes at most one document in the given collection that
matches selector.
To delete all matching documents, use mongoc_collection_delete_many().
If you pass a non-NULL reply, it is filled out with the field "deleted-
Count". If there is a server error then reply contains either a
"writeErrors" array with one subdocument or a "writeConcernErrors" ar-
ray. The reply must be freed with bson_destroy().
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_DELETE_ONE(3)
mongoc_collection_destroy.3
MONGOC_COLLECTION_DESTROY(3) libmongoc MONGOC_COLLECTION_DESTROY(3)
SYNOPSIS
void
mongoc_collection_destroy (mongoc_collection_t *collection);
PARAMETERS
+ collection: A mongoc_collection_t.
DESCRIPTION
This function shall destroy a mongoc_collection_t and its associated
resources. Does nothing if collection is NULL.
WARNING:
Always destroy a mongoc_cursor_t created from a collection before
destroying the collection.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_DESTROY(3)
mongoc_collection_drop.3
MONGOC_COLLECTION_DROP(3) libmongoc MONGOC_COLLECTION_DROP(3)
SYNOPSIS
bool
mongoc_collection_drop (mongoc_collection_t *collection, bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
For more information, see mongoc_collection_drop_with_opts(). This
function is a thin wrapper, passing NULL in as bson_t parameter.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_DROP(3)
mongoc_collection_drop_index.3
MONGOC_COLLECTION_DROP_INDEX(3) libmongoc MONGOC_COLLECTION_DROP_INDEX(3)
SYNOPSIS
bool
mongoc_collection_drop_index (mongoc_collection_t *collection,
const char *index_name,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ index_name: A string containing the name of the index.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
For more information, see mongoc_collection_drop_with_opts(). This
function is a thin wrapper, passing NULL in as bson_t parameter.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_DROP_INDEX(3)
mongoc_collection_drop_index_with_opts.3
MONGOC_COLLECTION_DROP_INDEX_WITH_OPTS(3)gocCOLLECTION_DROP_INDEX_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_collection_drop_index_with_opts (mongoc_collection_t *collection,
const char *index_name,
const bson_t *opts,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ index_name: A string containing the name of the index.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
DESCRIPTION
This function requests than an index on collection be dropped.
If no write concern is provided in opts, the collection's write concern
is used.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
SEE ALSO:
Manage Collection Indexes.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025OLLECTION_DROP_INDEX_WITH_OPTS(3)
mongoc_collection_drop_with_opts.3
MONGOC_COLLECTION_DROP_WITH_OPTS(3)libmongocONGOC_COLLECTION_DROP_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_collection_drop_with_opts (mongoc_collection_t *collection,
bson_t *opts,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
DESCRIPTION
This function requests that a collection be dropped, including all in-
dexes associated with the collection.
If no write concern is provided in opts, the collection's write concern
is used.
If the collection does not exist, the server responds with an "ns not
found" error. It is safe to ignore this error; set the Error API Ver-
sion to 2 and ignore server error code 26:
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bool r;
client = mongoc_client_new (NULL);
mongoc_client_set_error_api (client, 2);
collection = mongoc_client_get_collection (client, "db", "collection");
r = mongoc_collection_drop_with_opts (collection, NULL /* opts */, &error);
if (r) {
printf ("Dropped.\n");
} else {
printf ("Error message: %s\n", error.message);
if (error.domain == MONGOC_ERROR_SERVER && error.code == 26) {
printf ("Ignoring 'ns not found' error\n");
} else {
fprintf (stderr, "Unrecognized error!\n");
}
}
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
In MongoDB 3.0 and older, the "ns not found" error code is the generic
MONGOC_ERROR_QUERY_FAILURE; in this case check whether the error mes-
sage is equal to the string "ns not found".
The encryptedFields document in opts may be used to drop a collection
for Queryable Encryption. If encryptedFields is specified, the "ns not
found" error is not returned.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if the collection was successfully dropped. Returns false
and sets error if there are invalid arguments or a server or network
error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_COLLECTION_DROP_WITH_OPTS(3)
mongoc_collection_estimated_document_count.3
MONGOC_COLLECTION_ESTIMATED_DOCUMENTiCOUNT(3)CTION_ESTIMATED_DOCUMENT_COUNT(3)
SYNOPSIS
int64_t
mongoc_collection_estimated_document_count (mongoc_collection_t *collection,
const bson_t *opts,
const mongoc_read_prefs_t *read_prefs,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ opts: A bson_t, NULL to ignore.
+ read_prefs: A mongoc_read_prefs_t or NULL.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
+ skip: An int specifying how many documents matching the query should
be skipped before counting.
+ limit: An int specifying the maximum number of documents to count.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
For a list of all options, see the MongoDB Manual entry on the count
command.
DESCRIPTION
This functions executes a count query on collection. In contrast with
mongoc_collection_count_documents(), the count returned is not guaran-
teed to be accurate.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
Behavior
This method is implemented using the count command. Due to an oversight
in versions 5.0.0-5.0.8 of MongoDB, the count command was not included
in version "1" of the Stable API. Applications using this method with
the Stable API are recommended to upgrade their server version to
5.0.9+ or disable strict mode (via :symbol:`mongoc_server_api_strict())
to avoid encountering errors.
ERRORS
Errors are propagated via the error parameter.
RETURNS
-1 on failure, otherwise the number of documents counted.
EXAMPLE
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
static void
print_count (mongoc_collection_t *collection, bson_t *query)
{
bson_error_t error;
int64_t count;
bson_t* opts = BCON_NEW ("skip", BCON_INT64(5));
count = mongoc_collection_estimated_document_count (
collection, opts, NULL, NULL, &error);
bson_destroy (opts);
if (count < 0) {
fprintf (stderr, "Count failed: %s\n", error.message);
} else {
printf ("%" PRId64 " documents counted.\n", count);
}
}
SEE ALSO:
mongoc_collection_count_documents()
Count: Behavior in the MongoDB Manual
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,C2025CTION_ESTIMATED_DOCUMENT_COUNT(3)
mongoc_collection_find_and_modify.3
MONGOC_COLLECTION_FIND_AND_MODIFY(3)ibmongocNGOC_COLLECTION_FIND_AND_MODIFY(3)
SYNOPSIS
bool
mongoc_collection_find_and_modify (mongoc_collection_t *collection,
const bson_t *query,
const bson_t *sort,
const bson_t *update,
const bson_t *fields,
bool _remove,
bool upsert,
bool _new,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ query: A bson_t containing the query to locate target document(s).
+ sort: A bson_t containing the sort order for query.
+ update: A bson_t containing an update spec.
+ fields: An optional bson_t containing the fields to return or NULL.
+ _remove: If the matching documents should be removed.
+ upsert: If an upsert should be performed.
+ _new: If the new version of the document should be returned.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
Update and return an object.
This is a thin wrapper around the findAndModify command. Either update
or _remove arguments are required.
As of MongoDB 3.2, the mongoc_write_concern_t specified on the
mongoc_collection_t will be used, if any.
reply is always initialized, and must be freed with bson_destroy().
On success, the output reply contains the full server reply to the fin-
dAndModify command. See the MongoDB Manual page for findAndModify for
the expected server reply.
ERRORS
Errors are propagated via the error parameter.
RETURNS
If given invalid arguments or a server/network error occurs, returns
false and sets error. Otherwise, succeeds and returns true. A write
concern timeout or write concern error is considered a failure.
SEE ALSO:
mongoc_collection_find_and_modify_with_opts().
EXAMPLE
find-and-modify.c
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (void)
{
mongoc_collection_t *collection;
mongoc_client_t *client;
const char *uri_string = "mongodb://127.0.0.1:27017/?appname=find-and-modify-example";
mongoc_uri_t *uri;
bson_error_t error;
bson_t *query;
bson_t *update;
bson_t reply;
char *str;
mongoc_init ();
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
client = mongoc_client_new_from_uri (uri);
if (!client) {
return EXIT_FAILURE;
}
mongoc_client_set_error_api (client, 2);
collection = mongoc_client_get_collection (client, "test", "test");
/*
* Build our query, {"cmpxchg": 1}
*/
query = BCON_NEW ("cmpxchg", BCON_INT32 (1));
/*
* Build our update. {"$set": {"cmpxchg": 2}}
*/
update = BCON_NEW ("$set", "{", "cmpxchg", BCON_INT32 (2), "}");
/*
* Submit the findAndModify.
*/
if (!mongoc_collection_find_and_modify (collection, query, NULL, update, NULL, false, false, true, &reply, &error)) {
fprintf (stderr, "find_and_modify() failure: %s\n", error.message);
return EXIT_FAILURE;
}
/*
* Print the result as JSON.
*/
str = bson_as_canonical_extended_json (&reply, NULL);
printf ("%s\n", str);
bson_free (str);
/*
* Cleanup.
*/
bson_destroy (query);
bson_destroy (update);
bson_destroy (&reply);
mongoc_collection_destroy (collection);
mongoc_uri_destroy (uri);
mongoc_client_destroy (client);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_COLLECTION_FIND_AND_MODIFY(3)
mongoc_collection_find_and_modify_with_opts.3
MONGOC_COLLECTION_FIND_AND_MODIFYOWITHmOPTS(3)ION_FIND_AND_MODIFY_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_collection_find_and_modify_with_opts (
mongoc_collection_t *collection,
const bson_t *query,
const mongoc_find_and_modify_opts_t *opts,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ query: A bson_t containing the query to locate target document(s).
+ opts: A find and modify options. Must not be NULL.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
Update and return an object.
reply is always initialized, and must be freed with bson_destroy().
If an unacknowledged write concern is set (through
mongoc_find_and_modify_opts_append()), the output reply is always an
empty document.
On success, the output reply contains the full server reply to the fin-
dAndModify command. See the MongoDB Manual page for findAndModify for
the expected server reply.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
EXAMPLE
See the example code for mongoc_find_and_modify_opts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,O2025TION_FIND_AND_MODIFY_WITH_OPTS(3)
mongoc_collection_find_indexes_with_opts.3
MONGOC_COLLECTION_FIND_INDEXES_WITHlOPTS(3)cLLECTION_FIND_INDEXES_WITH_OPTS(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_collection_find_indexes_with_opts (mongoc_collection_t *collection,
const bson_t *opts);
Fetches a cursor containing documents, each corresponding to an index
on this collection.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
PARAMETERS
+ collection: A mongoc_collection_t.
+ opts: A bson_t containing additional options.
opts may be NULL or a BSON document with additional command options:
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
For a list of all options, see the MongoDB Manual entry on the listIn-
dexes command.
ERRORS
Use mongoc_cursor_error() on the returned cursor to check for errors.
RETURNS
This function returns a newly allocated mongoc_cursor_t that should be
freed with mongoc_cursor_destroy() when no longer in use. The returned
mongoc_cursor_t is never NULL, even on error. The user must call
mongoc_cursor_next() on the returned mongoc_cursor_t to execute the
initial command.
Cursor errors can be checked with mongoc_cursor_error_document(). It
always fills out the bson_error_t if an error occurred, and optionally
includes a server reply document if the error occurred server-side.
WARNING:
Failure to handle the result of this function is a programming er-
ror.
In the returned cursor each result corresponds to the server's repre-
sentation of an index on this collection. If the collection does not
exist on the server, the cursor will be empty.
The cursor functions mongoc_cursor_set_limit(),
mongoc_cursor_set_batch_size(), and
mongoc_cursor_set_max_await_time_ms() have no use on the returned cur-
sor.
SEE ALSO:
Manage Collection Indexes.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025LECTION_FIND_INDEXES_WITH_OPTS(3)
mongoc_collection_find_with_opts.3
MONGOC_COLLECTION_FIND_WITH_OPTS(3)libmongocONGOC_COLLECTION_FIND_WITH_OPTS(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_collection_find_with_opts (mongoc_collection_t *collection,
const bson_t *filter,
const bson_t *opts,
const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ collection: A mongoc_collection_t.
+ filter: A bson_t containing the query to execute.
+ opts: A bson_t query options, including sort order and which fields
to return. Can be NULL.
+ read_prefs: A mongoc_read_prefs_t or NULL.
DESCRIPTION
Query on collection, passing arbitrary query options to the server in
opts.
To target a specific server, include an integer "serverId" field in
opts with an id obtained first by calling
mongoc_client_select_server(), then mongoc_server_description_id() on
its return value.
Read preferences, read concern, and collation can be overridden by var-
ious sources. In a transaction, read concern and write concern are pro-
hibited in opts and the read preference must be primary or NULL. The
highest-priority sources for these options are listed first in the fol-
lowing table. No write concern is applied.
+-----------------+--------------+-----------+
|Read Preferences | Read Concern | Collation |
+-----------------+--------------+-----------+
|read_prefs | opts | opts |
+-----------------+--------------+-----------+
|Transaction | Transaction | |
+-----------------+--------------+-----------+
|collection | | |
+-----------------+--------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
RETURNS
This function returns a newly allocated mongoc_cursor_t that should be
freed with mongoc_cursor_destroy() when no longer in use. The returned
mongoc_cursor_t is never NULL, even on error. The user must call
mongoc_cursor_next() on the returned mongoc_cursor_t to execute the
initial command.
Cursor errors can be checked with mongoc_cursor_error_document(). It
always fills out the bson_error_t if an error occurred, and optionally
includes a server reply document if the error occurred server-side.
WARNING:
Failure to handle the result of this function is a programming er-
ror.
EXAMPLES
Print First Ten Documents in a Collection
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
static void
print_ten_documents (mongoc_collection_t *collection)
{
bson_t *filter;
bson_t *opts;
mongoc_cursor_t *cursor;
bson_error_t error;
const bson_t *doc;
char *str;
/* filter by "foo": 1, order by "bar" descending */
filter = BCON_NEW ("foo", BCON_INT32 (1));
opts = BCON_NEW (
"limit", BCON_INT64 (10), "sort", "{", "bar", BCON_INT32 (-1), "}");
cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_canonical_extended_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
if (mongoc_cursor_error (cursor, &error)) {
fprintf (stderr, "An error occurred: %s\n", error.message);
}
mongoc_cursor_destroy (cursor);
bson_destroy (filter);
bson_destroy (opts);
}
More examples of modifying the query with opts:
bson_t *filter;
bson_t *opts;
mongoc_read_prefs_t *read_prefs;
filter = BCON_NEW ("foo", BCON_INT32 (1));
/* Include "field_name_one" and "field_name_two" in "projection", omit
* others. "_id" must be specifically removed or it is included by default.
*/
opts = BCON_NEW ("projection", "{",
"field_name_one", BCON_BOOL (true),
"field_name_two", BCON_BOOL (true),
"_id", BCON_BOOL (false),
"}",
"tailable", BCON_BOOL (true),
"awaitData", BCON_BOOL (true),
"sort", "{", "bar", BCON_INT32 (-1), "}",
"collation", "{",
"locale", BCON_UTF8("en_US"),
"caseFirst", BCON_UTF8 ("lower"),
"}");
read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
cursor =
mongoc_collection_find_with_opts (collection, filter, opts, read_prefs);
The following options are supported.
+----------------+------------------+-----------------+--------------+
|Option | BSON type | Option | BSON type |
+----------------+------------------+-----------------+--------------+
|projection | document | max | document |
+----------------+------------------+-----------------+--------------+
|sort | document | maxTimeMS | non-negative |
| | | | int64 |
+----------------+------------------+-----------------+--------------+
|skip | non-negative | maxAwaitTimeMS | non-negative |
| | int64 | | int64 |
+----------------+------------------+-----------------+--------------+
|limit | non-negative | min | document |
| | int64 | | |
+----------------+------------------+-----------------+--------------+
|batchSize | non-negative | noCursorTimeout | bool |
| | int64 | | |
+----------------+------------------+-----------------+--------------+
|exhaust | bool | oplogReplay | bool |
+----------------+------------------+-----------------+--------------+
|hint | string or docu- | readConcern | document |
| | ment | | |
+----------------+------------------+-----------------+--------------+
|allowPartialRe- | bool | returnKey | bool |
|sults | | | |
+----------------+------------------+-----------------+--------------+
|awaitData | bool | sessionId | (none) |
+----------------+------------------+-----------------+--------------+
|collation | document | showRecordId | bool |
+----------------+------------------+-----------------+--------------+
|comment | any | singleBatch | bool |
+----------------+------------------+-----------------+--------------+
|allowDiskUse | bool | let | document |
+----------------+------------------+-----------------+--------------+
All options are documented in the reference page for the "find" command
in the MongoDB server manual, except for "maxAwaitTimeMS", "sessionId",
and "exhaust".
"maxAwaitTimeMS" is the maximum amount of time for the server to wait
on new documents to satisfy a query, if "tailable" and "awaitData" are
both true. If no new documents are found, the tailable cursor receives
an empty batch. The "maxAwaitTimeMS" option is ignored for MongoDB
older than 3.4.
To add a "sessionId", construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from col-
lection. Then use mongoc_client_session_append() to add the session to
opts. See the example code for mongoc_client_session_t.
To add a "readConcern", construct a mongoc_read_concern_t with
mongoc_read_concern_new() and configure it with
mongoc_read_concern_set_level(). Then use mongoc_read_concern_append()
to add the read concern to opts.
"exhaust" requests the construction of an exhaust cursor.
For some options like "collation", the driver returns an error if the
server version is too old to support the feature. Any fields in opts
that are not listed here are passed to the server unmodified.
allowDiskUse is only supported in MongoDB 4.4+.
comment only supports string values prior to MongoDB 4.4.
DEPRECATED OPTIONS
The snapshot boolean option is removed in MongoDB 4.0. The maxScan op-
tion, a non-negative int64, is deprecated in MongoDB 4.0 and will be
removed in a future MongoDB version. The oplogReplay boolean option is
deprecated in MongoDB 4.4. All of these options are supported by the C
Driver with older MongoDB versions.
SEE ALSO:
The "find" command in the MongoDB Manual. All options listed there are supported by the C Driver. For MongoDB servers before 3.2, the driver transparently converts the query to a legacy OP_QUERY message.
THE EXPLAIN COMMAND
With MongoDB before 3.2, a query with option $explain: true returns in-
formation about the query plan, instead of the query results. Beginning
in MongoDB 3.2, there is a separate "explain" command. The driver will
not convert "$explain" queries to "explain" commands, you must call the
"explain" command explicitly:
/* MongoDB 3.2+, "explain" command syntax */
command = BCON_NEW ("explain", "{",
"find", BCON_UTF8 ("collection_name"),
"filter", "{", "foo", BCON_INT32 (1), "}",
"}");
mongoc_collection_command_simple (collection, command, NULL, &reply, &error);
SEE ALSO:
The "explain" command in the MongoDB Manual.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_COLLECTION_FIND_WITH_OPTS(3)
mongoc_collection_get_name.3
MONGOC_COLLECTION_GET_NAME(3) libmongoc MONGOC_COLLECTION_GET_NAME(3)
SYNOPSIS
const char *
mongoc_collection_get_name (mongoc_collection_t *collection);
PARAMETERS
+ collection: A mongoc_collection_t.
DESCRIPTION
Fetches the name of collection.
RETURNS
A string which should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_GET_NAME(3)
mongoc_collection_get_read_concern.3
MONGOC_COLLECTION_GET_READ_CONCERN(3)bmongocGOC_COLLECTION_GET_READ_CONCERN(3)
SYNOPSIS
const mongoc_read_concern_t *
mongoc_collection_get_read_concern (const mongoc_collection_t *collection);
PARAMETERS
+ collection: A mongoc_collection_t.
DESCRIPTION
Fetches the default read concern to be used on read operations origi-
nating from collection.
RETURNS
A mongoc_read_concern_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_COLLECTION_GET_READ_CONCERN(3)
mongoc_collection_get_read_prefs.3
MONGOC_COLLECTION_GET_READ_PREFS(3)libmongocONGOC_COLLECTION_GET_READ_PREFS(3)
SYNOPSIS
const mongoc_read_prefs_t *
mongoc_collection_get_read_prefs (const mongoc_collection_t *collection);
PARAMETERS
+ collection: A mongoc_collection_t.
DESCRIPTION
Fetches the default read preferences to use for collection. Operations
without specified read-preferences will default to this.
RETURNS
A mongoc_read_prefs_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_COLLECTION_GET_READ_PREFS(3)
mongoc_collection_get_write_concern.3
MONGOC_COLLECTION_GET_WRITE_CONCERN(3)mongocOC_COLLECTION_GET_WRITE_CONCERN(3)
SYNOPSIS
const mongoc_write_concern_t *
mongoc_collection_get_write_concern (const mongoc_collection_t *collection);
PARAMETERS
+ collection: A mongoc_collection_t.
DESCRIPTION
Fetches the default write concern to be used on write operations origi-
nating from collection and not specifying a write concern.
RETURNS
A mongoc_write_concern_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_COLLECTION_GET_WRITE_CONCERN(3)
mongoc_collection_insert.3
MONGOC_COLLECTION_INSERT(3) libmongoc MONGOC_COLLECTION_INSERT(3)
SYNOPSIS
bool
mongoc_collection_insert (mongoc_collection_t *collection,
mongoc_insert_flags_t flags,
const bson_t *document,
const mongoc_write_concern_t *write_concern,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ flags: A mongoc_insert_flags_t.
+ document: A bson_t.
+ write_concern: A mongoc_write_concern_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
NOTE:
To pass additional options, use mongoc_collection_insert_one() or
mongoc_collection_insert_many().
This function shall insert document into collection.
If no _id element is found in document, then a bson_oid_t will be gen-
erated locally and added to the document. If you must know the inserted
document's _id, generate it in your code and include it in the docu-
ment. The _id you generate can be a bson_oid_t or any other non-array
BSON type.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_INSERT(3)
mongoc_collection_insert_many.3
MONGOC_COLLECTION_INSERT_MANY(3) libmongoc MONGOC_COLLECTION_INSERT_MANY(3)
SYNOPSIS
bool
mongoc_collection_insert_many (mongoc_collection_t *collection,
const bson_t **documents,
size_t n_documents,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ documents: An array of pointers to bson_t.
+ n_documents: The length of documents.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
+ ordered: set to false to attempt to insert all documents, continuing
after errors.
+ bypassDocumentValidation: Set to true to skip server-side schema val-
idation of the provided BSON documents.
DESCRIPTION
Insert documents into collection.
To insert a single document, see mongoc_collection_insert_one().
For any document that does not have an "_id" field, a bson_oid_t will
be generated locally and added to the document. If you must know the
inserted document's _id, generate it in your code and include it in the
document. The _id you generate can be a bson_oid_t or any other non-ar-
ray BSON type.
If you pass a non-NULL reply, it is filled out with an "insertedCount"
field. If there is a server error then reply may contain a "writeEr-
rors" array and/or a "writeConcernErrors" array (see Bulk Write Opera-
tions for examples). The reply must be freed with bson_destroy().
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_INSERT_MANY(3)
mongoc_collection_insert_one.3
MONGOC_COLLECTION_INSERT_ONE(3) libmongoc MONGOC_COLLECTION_INSERT_ONE(3)
SYNOPSIS
bool
mongoc_collection_insert_one (mongoc_collection_t *collection,
const bson_t *document,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ document: A bson_t.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
+ bypassDocumentValidation: Set to true to skip server-side schema val-
idation of the provided BSON documents.
DESCRIPTION
This function shall insert document into collection.
To insert an array of documents, see mongoc_collection_insert_many().
If no _id element is found in document, then a bson_oid_t will be gen-
erated locally and added to the document.
If you pass a non-NULL reply, it is filled out with an "insertedCount"
field. If the document was successfully inserted, reply will also con-
tain an "insertedId" field containing the inserted document's _id. If
there is a server error then reply contains either a "writeErrors" ar-
ray with one subdocument or a "writeConcernErrors" array. The reply
must be freed with bson_destroy().
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_INSERT_ONE(3)
mongoc_collection_keys_to_index_string.3
MONGOC_COLLECTION_KEYS_TO_INDEX_STRING(3)gocCOLLECTION_KEYS_TO_INDEX_STRING(3)
SYNOPSIS
char *
mongoc_collection_keys_to_index_string (const bson_t *keys);
PARAMETERS
+ keys: A bson_t. This is expected to match the form of the key field
in the createIndexes command.
DESCRIPTION
This function returns the canonical stringification of a given key
specification. See Manage Collection Indexes for example usage.
It is a programming error to call this function on a non-standard in-
dex, such one other than a straight index with ascending and descend-
ing.
RETURNS
A string that should be freed with bson_free().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025OLLECTION_KEYS_TO_INDEX_STRING(3)
mongoc_collection_read_command_with_opts.3
MONGOC_COLLECTION_READ_COMMAND_WITHlOPTS(3)cLLECTION_READ_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_collection_read_command_with_opts (mongoc_collection_t *collection,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, applying logic that is specific to
commands that read, and taking the MongoDB server version into account.
To send a raw command to the server without any of this logic, use
mongoc_collection_command_simple().
Use this function for commands that read such as "count" or "distinct".
Read preferences, read concern, and collation can be overridden by var-
ious sources. In a transaction, read concern and write concern are pro-
hibited in opts and the read preference must be primary or NULL. The
highest-priority sources for these options are listed first in the fol-
lowing table. No write concern is applied.
+-----------------+--------------+-----------+
|Read Preferences | Read Concern | Collation |
+-----------------+--------------+-----------+
|read_prefs | opts | opts |
+-----------------+--------------+-----------+
|Transaction | Transaction | |
+-----------------+--------------+-----------+
|collection | | |
+-----------------+--------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
reply is always initialized, and must be freed with bson_destroy().
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
Retry logic occurs regardless of the underlying command. Retrying
mapReduce has the potential for degraded performance. Retrying a get-
More command has the potential to miss results. For those commands, use
generic command helpers (like mongoc_collection_command_with_opts())
instead.
PARAMETERS
+ collection: A mongoc_collection_t.
+ command: A bson_t containing the command specification.
+ read_prefs: An optional mongoc_read_prefs_t.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025LECTION_READ_COMMAND_WITH_OPTS(3)
mongoc_collection_read_write_command_with_opts.3
MONGOC_COLLECTION_READ_WRITE_COMMANDiWITHgOPTS(3)AD_WRITE_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_collection_read_write_command_with_opts (
mongoc_collection_t *collection,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs /* UNUSED */,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, applying logic for commands that both
read and write, and taking the MongoDB server version into account. To
send a raw command to the server without any of this logic, use
mongoc_collection_command_simple().
Use this function for commands that both read and write, such as
"mapReduce" with an output collection.
Read and write concern and collation can be overridden by various
sources. In a transaction, read concern and write concern are prohib-
ited in opts. The highest-priority sources for these options are listed
first in the following table. Read preferences are not applied. The
write concern is omitted for MongoDB before 3.4.
+-------------+---------------+-----------+
|Read Concern | Write Concern | Collation |
+-------------+---------------+-----------+
|opts | opts | opts |
+-------------+---------------+-----------+
|Transaction | Transaction | |
+-------------+---------------+-----------+
|collection | collection | |
+-------------+---------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
reply is always initialized, and must be freed with bson_destroy().
(The mongoc_read_prefs_t parameter was included by mistake when this
function was introduced in libmongoc 1.5. A command that writes must
not obey a read preference.)
PARAMETERS
+ collection: A mongoc_collection_t.
+ command: A bson_t containing the command specification.
+ read_prefs: Ignored.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayC12,E2025N_READ_WRITE_COMMAND_WITH_OPTS(3)
mongoc_collection_remove.3
MONGOC_COLLECTION_REMOVE(3) libmongoc MONGOC_COLLECTION_REMOVE(3)
SYNOPSIS
bool
mongoc_collection_remove (mongoc_collection_t *collection,
mongoc_remove_flags_t flags,
const bson_t *selector,
const mongoc_write_concern_t *write_concern,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ flags: A mongoc_remove_flags_t.
+ selector: A bson_t containing the query to match documents.
+ write_concern: A mongoc_write_concern_t or NULL.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
NOTE:
To pass additional options, use mongoc_collection_delete_one() or
mongoc_collection_delete_many().
This function shall remove documents in the given collection that match
selector. The bson selector is not validated, simply passed along as
appropriate to the server. As such, compatibility and errors should be
validated in the appropriate server documentation.
If you want to limit deletes to a single document, provide MONGOC_RE-
MOVE_SINGLE_REMOVE in flags.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_REMOVE(3)
mongoc_collection_rename.3
MONGOC_COLLECTION_RENAME(3) libmongoc MONGOC_COLLECTION_RENAME(3)
SYNOPSIS
bool
mongoc_collection_rename (mongoc_collection_t *collection,
const char *new_db,
const char *new_name,
bool drop_target_before_rename,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ new_db: The name of the new database.
+ new_name: The new name for the collection.
+ drop_target_before_rename: If an existing collection matches the new
name, drop it before the rename.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
For more information, see mongoc_collection_rename_with_opts(). This
function is a thin wrapper, passing NULL in as bson_t parameter.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_RENAME(3)
mongoc_collection_rename_with_opts.3
MONGOC_COLLECTION_RENAME_WITH_OPTS(3)bmongocGOC_COLLECTION_RENAME_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_collection_rename_with_opts (mongoc_collection_t *collection,
const char *new_db,
const char *new_name,
bool drop_target_before_rename,
const bson_t *opts,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ new_db: The name of the new database.
+ new_name: The new name for the collection.
+ drop_target_before_rename: If an existing collection matches the new
name, drop it before the rename.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
DESCRIPTION
This function is a helper to rename an existing collection on a MongoDB
server. The name of the collection will also be updated internally so
it is safe to continue using this collection after the rename. Addi-
tional operations will occur on renamed collection.
If no write concern is provided in opts, the collection's write concern
is used.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_COLLECTION_RENAME_WITH_OPTS(3)
mongoc_collection_replace_one.3
MONGOC_COLLECTION_REPLACE_ONE(3) libmongoc MONGOC_COLLECTION_REPLACE_ONE(3)
SYNOPSIS
bool
mongoc_collection_replace_one (mongoc_collection_t *collection,
const bson_t *selector,
const bson_t *replacement,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ selector: A bson_t containing the query to match the document for up-
dating.
+ replacement: A bson_t containing the replacement document.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
+ bypassDocumentValidation: Set to true to skip server-side schema val-
idation of the provided BSON documents.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
+ upsert: When true, creates a new document if no document matches the
query.
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
+ sort: Specify a sort order when matching documents.
DESCRIPTION
This function shall replace documents in collection that match selector
with replacement.
If provided, reply will be initialized and populated with the fields
matchedCount, modifiedCount, upsertedCount, and optionally upsertedId
if applicable. If there is a server error then reply contains either a
writeErrors array with one subdocument or a writeConcernErrors array.
The reply must be freed with bson_destroy().
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
SEE ALSO:
MongoDB update command documentation for more information on the update options.
mongoc_collection_update_one()
mongoc_collection_update_many()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_REPLACE_ONE(3)
mongoc_collection_set_read_concern.3
MONGOC_COLLECTION_SET_READ_CONCERN(3)bmongocGOC_COLLECTION_SET_READ_CONCERN(3)
SYNOPSIS
void
mongoc_collection_set_read_concern (mongoc_collection_t *collection,
const mongoc_read_concern_t *read_concern);
PARAMETERS
+ collection: A mongoc_collection_t.
+ read_concern: A mongoc_read_concern_t.
DESCRIPTION
Sets the read concern to use for operations on collection.
The default read concern is empty: No readConcern is sent to the server
unless explicitly configured.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_COLLECTION_SET_READ_CONCERN(3)
mongoc_collection_set_read_prefs.3
MONGOC_COLLECTION_SET_READ_PREFS(3)libmongocONGOC_COLLECTION_SET_READ_PREFS(3)
SYNOPSIS
void
mongoc_collection_set_read_prefs (mongoc_collection_t *collection,
const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ collection: A mongoc_collection_t.
+ read_prefs: A mongoc_read_prefs_t.
DESCRIPTION
Sets the default read preferences to use for operations on collection
not specifying a read preference.
The global default is MONGOC_READ_PRIMARY: if the client is connected
to a replica set it reads from the primary, otherwise it reads from the
current MongoDB server.
Please see the MongoDB website for a description of Read Preferences.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_COLLECTION_SET_READ_PREFS(3)
mongoc_collection_set_write_concern.3
MONGOC_COLLECTION_SET_WRITE_CONCERN(3)mongocOC_COLLECTION_SET_WRITE_CONCERN(3)
SYNOPSIS
void
mongoc_collection_set_write_concern (
mongoc_collection_t *collection,
const mongoc_write_concern_t *write_concern);
PARAMETERS
+ collection: A mongoc_collection_t.
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Sets the write concern to use for operations on collection.
The default write concern is MONGOC_WRITE_CONCERN_W_DEFAULT: the driver
blocks awaiting basic acknowledgement of write operations from MongoDB.
This is the correct write concern for the great majority of applica-
tions.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_COLLECTION_SET_WRITE_CONCERN(3)
mongoc_collection_t.3
MONGOC_COLLECTION_T(3) libmongoc MONGOC_COLLECTION_T(3)
SYNOPSIS
typedef struct _mongoc_collection_t mongoc_collection_t;
mongoc_collection_t provides access to a MongoDB collection. This han-
dle is useful for actions for most CRUD operations, I.e. insert, up-
date, 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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_T(3)
mongoc_collection_update.3
MONGOC_COLLECTION_UPDATE(3) libmongoc MONGOC_COLLECTION_UPDATE(3)
SYNOPSIS
bool
mongoc_collection_update (mongoc_collection_t *collection,
mongoc_update_flags_t flags,
const bson_t *selector,
const bson_t *update,
const mongoc_write_concern_t *write_concern,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ flags: A bitwise or of mongoc_update_flags_t.
+ selector: A bson_t containing the query to match documents for updat-
ing.
+ update: A bson_t containing the update to perform. If updating with a
pipeline, a bson_t array.
+ write_concern: A mongoc_write_concern_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
NOTE:
To pass additional options, use mongoc_collection_update_one(),
mongoc_collection_update_many(), or mongoc_collection_replace_one().
This function shall update documents in collection that match selector.
By default, updates only a single document. Set flags to MONGOC_UP-
DATE_MULTI_UPDATE to update multiple documents.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_UPDATE(3)
mongoc_collection_update_many.3
MONGOC_COLLECTION_UPDATE_MANY(3) libmongoc MONGOC_COLLECTION_UPDATE_MANY(3)
SYNOPSIS
bool
mongoc_collection_update_many (mongoc_collection_t *collection,
const bson_t *selector,
const bson_t *update,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ selector: A bson_t containing the query to match documents for updat-
ing.
+ update: A bson_t containing the update to perform. If updating with a
pipeline, a bson_t array.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
+ bypassDocumentValidation: Set to true to skip server-side schema val-
idation of the provided BSON documents.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
+ upsert: When true, creates a new document if no document matches the
query.
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
+ arrayFilters: An array of filters specifying to which array elements
an update should apply.
DESCRIPTION
This function updates all documents in collection that match selector.
To update at most one document see mongoc_collection_update_one().
If you pass a non-NULL reply, it is filled out with fields matched-
Count, modifiedCount, and optionally upsertedId if applicable. If there
is a server error then reply contains either a "writeErrors" array with
one subdocument or a "writeConcernErrors" array. The reply must be
freed with bson_destroy().
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
SEE ALSO:
MongoDB update command documentation for more information on the update options.
mongoc_collection_update_one()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_UPDATE_MANY(3)
mongoc_collection_update_one.3
MONGOC_COLLECTION_UPDATE_ONE(3) libmongoc MONGOC_COLLECTION_UPDATE_ONE(3)
SYNOPSIS
bool
mongoc_collection_update_one (mongoc_collection_t *collection,
const bson_t *selector,
const bson_t *update,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ collection: A mongoc_collection_t.
+ selector: A bson_t containing the query to match the document for up-
dating.
+ update: A bson_t containing the update to perform. If updating with a
pipeline, a bson_t array.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ validate: Construct a bitwise-or of all desired
bson_validate_flags_t. Set to false to skip client-side validation of
the provided BSON documents.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
+ bypassDocumentValidation: Set to true to skip server-side schema val-
idation of the provided BSON documents.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ hint: A document or string that specifies the index to use to support
the query predicate.
+ upsert: When true, creates a new document if no document matches the
query.
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
+ arrayFilters: An array of filters specifying to which array elements
an update should apply.
+ sort: Specify a sort order when matching documents.
DESCRIPTION
This function updates at most one document in collection that matches
selector.
To update multiple documents see mongoc_collection_update_many().
If you pass a non-NULL reply, it is filled out with fields matched-
Count, modifiedCount, and optionally upsertedId if applicable. If there
is a server error then reply contains either a "writeErrors" array with
one subdocument or a "writeConcernErrors" array. The reply must be
freed with bson_destroy().
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
EXAMPLE
example-update.c
#include <mongoc/mongoc.h>
int
main (void)
{
mongoc_init ();
bson_t *to_insert = BCON_NEW ("_id", BCON_INT32 (1));
bson_t *selector = BCON_NEW ("_id", "{", "$gt", BCON_INT32 (0), "}");
bson_t *update = BCON_NEW ("$set", "{", "x", BCON_INT32 (1), "}");
const bson_t *next_doc;
char *to_str;
bson_error_t error = {0};
mongoc_cursor_t *cursor;
mongoc_client_t *client;
mongoc_collection_t *coll;
const char *uri_string = "mongodb://localhost:27017/?appname=example-update";
mongoc_uri_t *uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
client = mongoc_client_new_from_uri (uri);
if (!client) {
return EXIT_FAILURE;
}
coll = mongoc_client_get_collection (client, "db", "example_coll");
mongoc_client_set_error_api (client, 2);
/* insert a document */
if (!mongoc_collection_insert_one (coll, to_insert, NULL, NULL, &error)) {
fprintf (stderr, "insert failed: %s\n", error.message);
return EXIT_FAILURE;
}
if (!mongoc_collection_update_one (coll, selector, update, NULL, NULL, &error)) {
fprintf (stderr, "update failed: %s\n", error.message);
return EXIT_FAILURE;
}
to_str = bson_as_relaxed_extended_json (to_insert, NULL);
printf ("inserted: %s\n", to_str);
bson_free (to_str);
cursor = mongoc_collection_find_with_opts (coll, selector, NULL, NULL);
BSON_ASSERT (mongoc_cursor_next (cursor, &next_doc));
printf ("after update, collection has the following document:\n");
to_str = bson_as_relaxed_extended_json (next_doc, NULL);
printf ("%s\n", to_str);
bson_free (to_str);
BSON_ASSERT (mongoc_collection_drop (coll, NULL));
bson_destroy (to_insert);
bson_destroy (update);
bson_destroy (selector);
mongoc_collection_destroy (coll);
mongoc_uri_destroy (uri);
mongoc_client_destroy (client);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
SEE ALSO:
MongoDB update command documentation for more information on the update options.
mongoc_collection_update_many()
mongoc_collection_replace_one()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_UPDATE_ONE(3)
mongoc_collection_watch.3
MONGOC_COLLECTION_WATCH(3) libmongoc MONGOC_COLLECTION_WATCH(3)
SYNOPSIS
mongoc_change_stream_t*
mongoc_collection_watch (const mongoc_collection_t *coll,
const bson_t *pipeline,
const bson_t *opts);
A helper function to create a change stream. It is preferred to call
this function over using a raw aggregation to create a change stream.
This function uses the read preference and read concern of the collec-
tion. If the change stream needs to re-establish connection, the same
read preference will be used. This may happen if the change stream en-
counters a resumable error.
WARNING:
A change stream is only supported with majority read concern.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
PARAMETERS
+ coll: A mongoc_collection_t specifying the collection which the
change stream listens to.
+ pipeline: A bson_t representing an aggregation pipeline appended to
the change stream. This may be an empty document.
+ opts: A bson_t containing change stream options.
Changed in version 2.0.0: batchSize of 0 is applied to the aggregate
command. 0 was previously ignored.
opts may be NULL or a BSON document with additional command options:
+ batchSize: An int32 requesting a limit of documents returned in each
server reply. If positive, the batchSize is applied to both aggregate
and getMore commands. If 0, the batchSize is only applied to the ag-
gregate command (Useful to request an immediate cursor without sig-
nificant server-side work. See Aggregate Data Specifying Batch Size).
If omitted or negative, the value is ignored and server defaults are
used (See Cursor Batches for a description of server defaults).
+ resumeAfter: A Document representing the logical starting point of
the change stream. The result of
mongoc_change_stream_get_resume_token() or the _id field of any
change received from a change stream can be used here. This option is
mutually exclusive with startAfter and startAtOperationTime.
+ startAfter: A Document representing the logical starting point of the
change stream. Unlike resumeAfter, this can resume notifications af-
ter an "invalidate" event. The result of
mongoc_change_stream_get_resume_token() or the _id field of any
change received from a change stream can be used here. This option
is mutually exclusive with resumeAfter and startAtOperationTime.
+ startAtOperationTime: A Timestamp. The change stream only provides
changes that occurred at or after the specified timestamp. Any com-
mand run against the server will return an operation time that can be
used here. This option is mutually exclusive with resumeAfter and
startAfter.
+ maxAwaitTimeMS: An int64 representing the maximum amount of time a
call to mongoc_change_stream_next() will block waiting for data
+ fullDocument: An optional UTF-8 string. Set this option to "default",
"updateLookup", "whenAvailable", or "required", If unset, The string
"default" is assumed. Set this option to "updateLookup" to direct the
change stream cursor to lookup the most current majority-committed
version of the document associated to an update change stream event.
+ fullDocumentBeforeChange: An optional UTF-8 string. Set this option
to "whenAvailable", "required", or "off". When unset, the default
value is "off". Similar to "fullDocument", but returns the value of
the document before the associated change.
+ showExpandedEvents: Set to true to return an expanded list of change
stream events. Available only on MongoDB versions >=6.0
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Only string values are supported prior to MongoDB
4.4.
RETURNS
A newly allocated mongoc_change_stream_t which must be freed with
mongoc_change_stream_destroy() when no longer in use. The returned
mongoc_change_stream_t is never NULL. If there is an error, it can be
retrieved with mongoc_change_stream_error_document(), and subsequent
calls to mongoc_change_stream_next() will return false.
SEE ALSO:
mongoc_client_watch()
mongoc_database_watch()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_COLLECTION_WATCH(3)
mongoc_collection_write_command_with_opts.3
MONGOC_COLLECTION_WRITE_COMMAND_WITHiOPTS(3)LECTION_WRITE_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_collection_write_command_with_opts (mongoc_collection_t *collection,
const bson_t *command,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, applying logic that is specific to
commands that write, and taking the MongoDB server version into ac-
count. To send a raw command to the server without any of this logic,
use mongoc_collection_command_simple().
Use this function for commands that write such as "drop" or "create-
Role" (but not for "insert", "update", or "delete", see Basic Write Op-
erations). Write concern and collation can be overridden by various
sources. In a transaction, read concern and write concern are prohib-
ited in opts. The highest-priority sources for these options are listed
first in the following table. The write concern is omitted for MongoDB
before 3.4.
+--------------+-----------+
|Write Concern | Collation |
+--------------+-----------+
|opts | opts |
+--------------+-----------+
|Transaction | |
+--------------+-----------+
|collection | |
+--------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
reply is always initialized, and must be freed with bson_destroy().
PARAMETERS
+ collection: A mongoc_collection_t.
+ command: A bson_t containing the command specification.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
BASIC WRITE OPERATIONS
Do not use this function to call the basic write commands "insert",
"update", and "delete". Those commands require special logic not imple-
mented in mongoc_collection_write_command_with_opts. For basic write
operations use CRUD functions such as mongoc_collection_insert_one()
and the others described in the CRUD tutorial, or use the Bulk API.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025ECTION_WRITE_COMMAND_WITH_OPTS(3)
mongoc_cursor_clone.3
MONGOC_CURSOR_CLONE(3) libmongoc MONGOC_CURSOR_CLONE(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_cursor_clone (const mongoc_cursor_t *cursor);
PARAMETERS
+ cursor: A mongoc_cursor_t.
DESCRIPTION
This function shall create a copy of a mongoc_cursor_t. The cloned cur-
sor will be reset to the beginning of the query, and therefore the
query will be re-executed on the MongoDB server when
mongoc_cursor_next() is called.
RETURNS
A newly allocated mongoc_cursor_t that should be freed with
mongoc_cursor_destroy() when no longer in use.
WARNING:
Failure to handle the result of this function is a programming er-
ror.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_CLONE(3)
mongoc_cursor_current.3
MONGOC_CURSOR_CURRENT(3) libmongoc MONGOC_CURSOR_CURRENT(3)
SYNOPSIS
const bson_t *
mongoc_cursor_current (const mongoc_cursor_t *cursor);
PARAMETERS
+ cursor: A mongoc_cursor_t.
DESCRIPTION
Fetches the cursors current document or NULL if there has been an er-
ror.
RETURNS
A bson_t that should not be modified or freed or NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_CURRENT(3)
mongoc_cursor_destroy.3
MONGOC_CURSOR_DESTROY(3) libmongoc MONGOC_CURSOR_DESTROY(3)
SYNOPSIS
void
mongoc_cursor_destroy (mongoc_cursor_t *cursor);
PARAMETERS
+ cursor: A mongoc_cursor_t.
DESCRIPTION
Frees a mongoc_cursor_t and releases all associated resources. If a
server-side cursor has been allocated, it will be released as well.
Does nothing if cursor is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_DESTROY(3)
mongoc_cursor_error.3
MONGOC_CURSOR_ERROR(3) libmongoc MONGOC_CURSOR_ERROR(3)
SYNOPSIS
bool
mongoc_cursor_error (mongoc_cursor_t *cursor, bson_error_t *error);
PARAMETERS
+ cursor: A mongoc_cursor_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
This function checks to see if an error has occurred while iterating
the cursor.
ERRORS
Errors are propagated via the error parameter.
RETURNS
false if no error has occurred, otherwise true and error is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_ERROR(3)
mongoc_cursor_error_document.3
MONGOC_CURSOR_ERROR_DOCUMENT(3) libmongoc MONGOC_CURSOR_ERROR_DOCUMENT(3)
SYNOPSIS
bool
mongoc_cursor_error_document (mongoc_cursor_t *cursor,
bson_error_t *error,
const bson_t **reply);
PARAMETERS
+ cursor: A mongoc_cursor_t.
+ error: An optional location for a bson_error_t or NULL.
+ reply: A location for a bson_t.
DESCRIPTION
This function checks to see if an error has occurred while iterating
the cursor.
If an error occurred client-side, for example if there was a network
error or timeout, or the cursor was created with invalid parameters,
then reply is set to an empty BSON document. If an error occurred
server-side, reply is set to the server's reply document with informa-
tion about the error.
ERRORS
Errors are propagated via the error and reply parameters.
RETURNS
False if no error has occurred, otherwise true and error is set.
If the function returns true and reply is not NULL, then reply is set
to a pointer to a BSON document, which is either empty or the server's
error response. The document is invalid after the cursor is freed with
mongoc_cursor_destroy().
EXAMPLE
This example shows the difference between a client-side and server-side
error. If the client cannot connect to the server, for example, the er-
ror message includes "No suitable servers found" and reply is set to an
empty BSON document.
On the other hand, if the client connects to the server successfully
and attempts to execute an invalid query, the error message comes from
the server and reply is set to the server's reply document, with fields
errmsg and code.
void
run_query (const char *uri_str, const bson_t *query)
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_error_t error;
const bson_t *reply;
char *str;
client = mongoc_client_new (uri_str);
mongoc_client_set_error_api (client, 2);
collection = mongoc_client_get_collection (client, "db", "collection");
cursor = mongoc_collection_find_with_opts (
collection,
query,
NULL, /* additional options */
NULL); /* read prefs, NULL for default */
/* this loop is never run: mongoc_cursor_next immediately returns false */
while (mongoc_cursor_next (cursor, &doc)) {
}
if (mongoc_cursor_error_document (cursor, &error, &reply)) {
str = bson_as_relaxed_extended_json (reply, NULL);
fprintf (stderr, "Cursor Failure: %s\nReply: %s\n", error.message, str);
bson_free (str);
}
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
}
int
main (int argc, char *argv[])
{
bson_t *good_query;
bson_t *bad_query;
mongoc_init ();
/* find documents matching the query {"x": 1} */
good_query = BCON_NEW ("x", BCON_INT64 (1));
/* Cause a network error. This will print an error and empty reply document:
*
* Cursor Failure: No suitable servers found (`serverSelectionTryOnce` set):
* [Failed to resolve 'fake-domain']
*
* Reply: { }
*
*/
run_query ("mongodb://fake-domain/?appname=cursor-example", good_query);
/* invalid: {"x": {"$badOperator": 1}} */
bad_query = BCON_NEW ("x", "{", "$badOperator", BCON_INT64 (1), "}");
/* Cause a server error. This will print an error and server reply document:
*
* Cursor Failure: unknown operator: $badOperator
*
* Reply:
* {"ok": 0.0,
* "errmsg":"unknown operator: $badOperator",
* "code": 2,
* "codeName":"BadValue"
* }
*
*/
run_query ("mongodb://localhost/?appname=cursor-example", bad_query);
bson_destroy (good_query);
bson_destroy (bad_query);
mongoc_cleanup ();
return 0;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_ERROR_DOCUMENT(3)
mongoc_cursor_get_batch_size.3
MONGOC_CURSOR_GET_BATCH_SIZE(3) libmongoc MONGOC_CURSOR_GET_BATCH_SIZE(3)
SYNOPSIS
uint32_t
mongoc_cursor_get_batch_size (const mongoc_cursor_t *cursor);
PARAMETERS
+ cursor: A mongoc_cursor_t.
DESCRIPTION
Retrieve the cursor's batch size, the maximum number of documents re-
turned per round trip to the server. A batch size of zero means the
cursor accepts the server's maximum batch size.
See Cursor Batches in the MongoDB Manual.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_GET_BATCH_SIZE(3)
mongoc_cursor_get_host.3
MONGOC_CURSOR_GET_HOST(3) libmongoc MONGOC_CURSOR_GET_HOST(3)
SYNOPSIS
void
mongoc_cursor_get_host (mongoc_cursor_t *cursor, mongoc_host_list_t *host);
PARAMETERS
+ cursor: A mongoc_cursor_t.
+ host: A mongoc_host_list_t.
DESCRIPTION
Fetches the MongoDB host that the cursor is communicating with in the
host out parameter.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_GET_HOST(3)
mongoc_cursor_get_id.3
MONGOC_CURSOR_GET_ID(3) libmongoc MONGOC_CURSOR_GET_ID(3)
SYNOPSIS
int64_t
mongoc_cursor_get_id (const mongoc_cursor_t *cursor);
PARAMETERS
+ cursor: A mongoc_cursor_t.
DESCRIPTION
Retrieves the cursor id used by the server to track the cursor.
This number is zero until the driver actually uses a server when exe-
cuting the query, and after it has fetched all results from the server.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_GET_ID(3)
mongoc_cursor_get_limit.3
MONGOC_CURSOR_GET_LIMIT(3) libmongoc MONGOC_CURSOR_GET_LIMIT(3)
SYNOPSIS
int64_t
mongoc_cursor_get_limit (mongoc_cursor_t *cursor);
PARAMETERS
+ cursor: A mongoc_cursor_t.
DESCRIPTION
Return the value set with mongoc_cursor_set_limit() or
mongoc_collection_find_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_GET_LIMIT(3)
mongoc_cursor_get_max_await_time_ms.3
MONGOC_CURSOR_GET_MAX_AWAIT_TIME_MS(3)mongocOC_CURSOR_GET_MAX_AWAIT_TIME_MS(3)
SYNOPSIS
uint32_t
mongoc_cursor_get_max_await_time_ms (mongoc_cursor_t *cursor);
PARAMETERS
+ cursor: A mongoc_cursor_t.
DESCRIPTION
Retrieve the value set with mongoc_cursor_set_max_await_time_ms().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_CURSOR_GET_MAX_AWAIT_TIME_MS(3)
mongoc_cursor_get_server_id.3
MONGOC_CURSOR_GET_SERVER_ID(3) libmongoc MONGOC_CURSOR_GET_SERVER_ID(3)
SYNOPSIS
uint32_t
mongoc_cursor_get_server_id (const mongoc_cursor_t *cursor);
PARAMETERS
+ cursor: A mongoc_cursor_t.
DESCRIPTION
Retrieves the opaque id of the server used for the operation.
This number is zero until the driver actually uses a server when exe-
cuting the find operation or mongoc_cursor_set_server_id() is called.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_GET_SERVER_ID(3)
mongoc_cursor_more.3
MONGOC_CURSOR_MORE(3) libmongoc MONGOC_CURSOR_MORE(3)
SYNOPSIS
bool
mongoc_cursor_more (mongoc_cursor_t *cursor);
PARAMETERS
+ cursor: A mongoc_cursor_t.
DESCRIPTION
This function shall indicate if there is potentially more data to be
read from the cursor. This is only useful with tailable cursors. Use
mongoc_cursor_next() for regular cursors.
Details: mongoc_cursor_more is unreliable because it does not contact
the server to see if there are actually more documents in the result
set. It simply returns true if the cursor has not begun, or if it has
begun and there are buffered documents in the client-side cursor, or if
it has begun and the server has not yet told the cursor it is com-
pletely iterated.
This is unreliable with regular queries because it returns true for a
new cursor before iteration, even if the cursor will match no docu-
ments. It is also true if the collection has been dropped on the server
since the previous fetch, or if the cursor has finished its final batch
and the next batch will be empty.
RETURNS
true if the cursor has locally-buffered documents, or if a round-trip
to the server might fetch additional documents.
SEE ALSO:
Tailable Cursor Example
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_MORE(3)
mongoc_cursor_new_from_command_reply_with_opts.3
MONGOC_CURSOR_NEW_FROM_COMMANDOREPLYiWITHgOPTS(3)OM_COMMAND_REPLY_WITH_OPTS(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_cursor_new_from_command_reply_with_opts (mongoc_client_t *client,
bson_t *reply,
const bson_t *opts);
PARAMETERS
+ client: A mongoc_client_t.
+ reply: The reply to a command, such as "aggregate", "find", or "list-
Collections", that returns a cursor document. The reply is destroyed
by mongoc_cursor_new_from_command_reply_with_opts and must not be ac-
cessed afterward.
+ opts: A bson_t.
opts may be NULL or a BSON document with additional options, which have
the same meaning for this function as for
mongoc_collection_find_with_opts():
+ awaitData
+ batchSize
+ limit
+ maxAwaitTimeMS
+ serverId
+ sessionId
+ skip
+ tailable
DESCRIPTION
Some MongoDB commands return a "cursor" document. For example, given an
"aggregate" command:
{ "aggregate" : "collection", "pipeline" : [], "cursor" : {}}
The server replies:
{
"cursor" : {
"id" : 1234,
"ns" : "db.collection",
"firstBatch" : [ ]
},
"ok" : 1
}
mongoc_cursor_new_from_command_reply_with_opts is a low-level function
that initializes a mongoc_cursor_t from such a reply.
When synthesizing a completed cursor response that has no more batches
(i.e. with cursor id 0), serverId may be 0. If the cursor response is
not completed (i.e. with non-zero cursor id), pass the serverId of the
server used to create the cursor.
Use this function only for building a language driver that wraps the C
Driver. When writing applications in C, higher-level functions such as
mongoc_collection_aggregate() are more appropriate, and ensure compati-
bility with a range of MongoDB versions.
RETURNS
A mongoc_cursor_t. On failure, the cursor's error is set. Check for
failure with mongoc_cursor_error().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayC12,O2025W_FROM_COMMAND_REPLY_WITH_OPTS(3)
mongoc_cursor_next.3
MONGOC_CURSOR_NEXT(3) libmongoc MONGOC_CURSOR_NEXT(3)
SYNOPSIS
bool
mongoc_cursor_next (mongoc_cursor_t *cursor, const bson_t **bson);
PARAMETERS
+ cursor: A mongoc_cursor_t.
+ bson: A location for a bson_t.
DESCRIPTION
This function shall iterate the underlying cursor, setting bson to the
next document.
This function is a blocking function.
RETURNS
This function returns true if a valid bson document was read from the
cursor. Otherwise, false if there was an error or the cursor was ex-
hausted.
Errors can be determined with the mongoc_cursor_error() function.
LIFECYCLE
The bson objects set in this function are ephemeral and good until the
next call. This means that you must copy the returned bson if you wish
to retain it beyond the lifetime of a single call to
mongoc_cursor_next().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_NEXT(3)
mongoc_cursor_set_batch_size.3
MONGOC_CURSOR_SET_BATCH_SIZE(3) libmongoc MONGOC_CURSOR_SET_BATCH_SIZE(3)
SYNOPSIS
void
mongoc_cursor_set_batch_size (mongoc_cursor_t *cursor, uint32_t batch_size);
PARAMETERS
+ cursor: A mongoc_cursor_t.
+ batch_size: The requested number of documents per batch.
DESCRIPTION
Limits the number of documents returned in one batch. Each batch re-
quires a round trip to the server. If the batch size is zero, the cur-
sor uses the server-defined maximum batch size.
See Cursor Batches in the MongoDB Manual.
This is not applicable to all cursors. Calling
mongoc_cursor_set_batch_size() on a cursor returned by
mongoc_client_find_databases_with_opts(),
mongoc_database_find_collections_with_opts(), or
mongoc_collection_find_indexes_with_opts() will not change the results.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_SET_BATCH_SIZE(3)
mongoc_cursor_set_limit.3
MONGOC_CURSOR_SET_LIMIT(3) libmongoc MONGOC_CURSOR_SET_LIMIT(3)
SYNOPSIS
bool
mongoc_cursor_set_limit (mongoc_cursor_t *cursor, int64_t limit);
PARAMETERS
+ cursor: A mongoc_cursor_t.
+ limit: The maximum number of documents to retrieve for this query.
DESCRIPTION
Limits the number of documents in the result set.
This function is useful for setting the limit on a cursor after the
cursor is created, but before any calls to mongoc_cursor_next(). It can
also be used to pass a negative limit: The limit parameter to mon-
goc_cursor_set_limit is signed.
Calling this function after mongoc_cursor_next() has no effect.
This is not applicable to all cursors. Calling
mongoc_cursor_set_limit() on a cursor returned by
mongoc_client_find_databases_with_opts(),
mongoc_database_find_collections_with_opts(), or
mongoc_collection_find_indexes_with_opts() will not change the results.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and leaves the limit unchanged.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_SET_LIMIT(3)
mongoc_cursor_set_max_await_time_ms.3
MONGOC_CURSOR_SET_MAX_AWAIT_TIME_MS(3)mongocOC_CURSOR_SET_MAX_AWAIT_TIME_MS(3)
SYNOPSIS
void
mongoc_cursor_set_max_await_time_ms (mongoc_cursor_t *cursor,
uint32_t max_await_time_ms);
PARAMETERS
+ cursor: A mongoc_cursor_t.
+ max_await_time_ms: A timeout in milliseconds.
DESCRIPTION
The maximum amount of time for the server to wait on new documents to
satisfy a tailable cursor query. Only applies if the cursor is created
from mongoc_collection_find_with_opts() with "tailable" and "awaitData"
options, and the server is MongoDB 3.2 or later. See the documentation
for maxTimeMS and the "getMore" command.
The max_await_time_ms cannot be changed after the first call to
mongoc_cursor_next().
This is not applicable to all cursors. Calling
mongoc_cursor_set_batch_size() on a cursor returned by
mongoc_client_find_databases_with_opts(),
mongoc_database_find_collections_with_opts(), or
mongoc_collection_find_indexes_with_opts() will not change the results.
Note: although max_await_time_ms is a uint32_t, it is possible to set
it as a uint64_t through the options arguments in some cursor returning
functions like mongoc_collection_find_with_opts().
SEE ALSO:
Tailable Cursors.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_CURSOR_SET_MAX_AWAIT_TIME_MS(3)
mongoc_cursor_set_server_id.3
MONGOC_CURSOR_SET_SERVER_ID(3) libmongoc MONGOC_CURSOR_SET_SERVER_ID(3)
SYNOPSIS
bool
mongoc_cursor_set_server_id (mongoc_cursor_t *cursor, uint32_t server_id)
PARAMETERS
+ cursor: A mongoc_cursor_t.
+ server_id: An opaque id identifying the server to use.
DESCRIPTION
Specifies which server to use for the operation. This function has an
effect only if called before the find operation is executed.
Use mongoc_cursor_set_server_id only for building a language driver
that wraps the C Driver. When writing applications in C, leave the
server id unset and allow the driver to choose a suitable server from
the find operation's read preference.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and logs an error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_SET_SERVER_ID(3)
mongoc_cursor_t.3
MONGOC_CURSOR_T(3) libmongoc MONGOC_CURSOR_T(3)
Client-side cursor abstraction
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.
Common cursor operations include:
+ 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().
Cursors are lazy, meaning that no connection is established and no net-
work traffic occurs until the first call to mongoc_cursor_next().
THREAD SAFETY
mongoc_cursor_t is NOT thread safe. It may only be used from within the
thread in which it was created.
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: %s\n"
"error message: %s\n",
uri_string,
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;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_CURSOR_T(3)
mongoc_database_add_user.3
MONGOC_DATABASE_ADD_USER(3) libmongoc MONGOC_DATABASE_ADD_USER(3)
SYNOPSIS
bool
mongoc_database_add_user (mongoc_database_t *database,
const char *username,
const char *password,
const bson_t *roles,
const bson_t *custom_data,
bson_error_t *error);
PARAMETERS
+ database: A mongoc_database_t.
+ username: The name of the user.
+ password: The cleartext password for the user.
+ roles: An optional bson_t for roles.
+ custom_data: A optional bson_t for extra data.
+ error: A location for a bson_error_t or NULL.
This function shall create a new user with access to database.
WARNING:
Do not call this function without TLS.
ERRORS
Errors are returned through the error parameter and can include socket
or other server side failures.
RETURNS
Returns true if the user was successfully added. Returns false and sets
error if there are invalid arguments or a server or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_DATABASE_ADD_USER(3)
mongoc_database_aggregate.3
MONGOC_DATABASE_AGGREGATE(3) libmongoc MONGOC_DATABASE_AGGREGATE(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_database_aggregate (mongoc_database_t *database,
const bson_t *pipeline,
const bson_t *opts,
const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ database: A mongoc_database_t.
+ pipeline: A bson_t, either a BSON array or a BSON document containing
an array field named "pipeline".
+ opts: A bson_t containing options for the command, or NULL.
+ read_prefs: A mongoc_read_prefs_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
database, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ bypassDocumentValidation: Set to true to skip server-side schema val-
idation of the provided BSON documents.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
+ batchSize: An int32 representing number of documents requested to be
returned on each call to mongoc_cursor_next()
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Only string values are supported prior to MongoDB
4.4.
+ hint: A document or string that specifies the index to use to support
the query predicate.
For a list of all options, see the MongoDB Manual entry on the aggre-
gate command.
DESCRIPTION
This function creates a cursor which sends the aggregate command on the
underlying database upon the first call to mongoc_cursor_next(). For
more information on building aggregation pipelines, see the MongoDB
Manual entry on the aggregate command. Note that the pipeline must
start with a compatible stage that does not require an underlying col-
lection (e.g. "$currentOp", "$listLocalSessions").
Read preferences, read and write concern, and collation can be overrid-
den by various sources. The highest-priority sources for these options
are listed first in the following table. In a transaction, read concern
and write concern are prohibited in opts and the read preference must
be primary or NULL. Write concern is applied from opts, or if opts has
no write concern and the aggregation pipeline includes "$out", the
write concern is applied from database.
+-----------------+--------------+---------------+-----------+
|Read Preferences | Read Concern | Write Concern | Collation |
+-----------------+--------------+---------------+-----------+
|read_prefs | opts | opts | opts |
+-----------------+--------------+---------------+-----------+
|Transaction | Transaction | Transaction | |
+-----------------+--------------+---------------+-----------+
|database | database | database | |
+-----------------+--------------+---------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
This function is considered a retryable read operation unless the pipe-
line contains a write stage like $out or $merge. Upon a transient er-
ror (a network error, errors due to replica set failover, etc.) the op-
eration is safely retried once. If retryreads is false in the URI (see
mongoc_uri_t) the retry behavior does not apply.
RETURNS
This function returns a newly allocated mongoc_cursor_t that should be
freed with mongoc_cursor_destroy() when no longer in use. The returned
mongoc_cursor_t is never NULL, even on error. The user must call
mongoc_cursor_next() on the returned mongoc_cursor_t to execute the
initial command.
Cursor errors can be checked with mongoc_cursor_error_document(). It
always fills out the bson_error_t if an error occurred, and optionally
includes a server reply document if the error occurred server-side.
WARNING:
Failure to handle the result of this function is a programming er-
ror.
EXAMPLE
#include <bson/bson.h>
#include <mongoc/mongoc.h>
static mongoc_cursor_t *
current_op_query (mongoc_client_t *client)
{
mongoc_cursor_t *cursor;
mongoc_database_t *database;
bson_t *pipeline;
pipeline = BCON_NEW ("pipeline",
"[",
"{",
"$currentOp",
"{",
"}",
"}",
"]");
/* $currentOp must be run on the admin database */
database = mongoc_client_get_database (client, "admin");
cursor = mongoc_database_aggregate (
database, pipeline, NULL, NULL);
bson_destroy (pipeline);
mongoc_database_destroy (database);
return cursor;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_DATABASE_AGGREGATE(3)
mongoc_database_command_simple.3
MONGOC_DATABASE_COMMAND_SIMPLE(3) libmongoc MONGOC_DATABASE_COMMAND_SIMPLE(3)
SYNOPSIS
bool
mongoc_database_command_simple (mongoc_database_t *database,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
bson_t *reply,
bson_error_t *error);
PARAMETERS
+ database: A mongoc_database_t.
+ command: A bson_t containing the command.
+ read_prefs: An optional mongoc_read_prefs_t. Otherwise, the command
uses mode MONGOC_READ_PRIMARY.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
The database's read preference, read concern, and write concern are not
applied to the command. The parameter reply is initialized even upon
failure to simplify memory management.
This function is not considered a retryable read operation.
ERRORS
Errors are propagated through the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
This function does not check the server response for a write concern
error or write concern timeout.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_DATABASE_COMMAND_SIMPLE(3)
mongoc_database_command_with_opts.3
MONGOC_DATABASE_COMMAND_WITH_OPTS(3)ibmongocNGOC_DATABASE_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_database_command_with_opts (
mongoc_database_t *database,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, interpreting opts according to the
MongoDB server version. To send a raw command to the server without any
of this logic, use mongoc_client_command_simple().
Read preferences, read and write concern, and collation can be overrid-
den by various sources. The highest-priority sources for these options
are listed first:
+-----------------+--------------+---------------+-----------+
|Read Preferences | Read Concern | Write Concern | Collation |
+-----------------+--------------+---------------+-----------+
|read_prefs | opts | opts | opts |
+-----------------+--------------+---------------+-----------+
|Transaction | Transaction | Transaction | |
+-----------------+--------------+---------------+-----------+
In a transaction, read concern and write concern are prohibited in opts
and the read preference must be primary or NULL. See the example for
transactions and for the "distinct" command with opts.
reply is always initialized, and must be freed with bson_destroy().
This function is not considered a retryable read operation.
PARAMETERS
+ database: A mongoc_database_t.
+ command: A bson_t containing the command specification.
+ read_prefs: An optional mongoc_read_prefs_t.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
database, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
The reply is not parsed for a write concern timeout or write concern
error.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_DATABASE_COMMAND_WITH_OPTS(3)
mongoc_database_copy.3
MONGOC_DATABASE_COPY(3) libmongoc MONGOC_DATABASE_COPY(3)
SYNOPSIS
mongoc_database_t *
mongoc_database_copy (mongoc_database_t *database);
PARAMETERS
+ database: A mongoc_database_t.
DESCRIPTION
Performs a deep copy of the database struct and its configuration. Use-
ful if you intend to call mongoc_database_set_write_concern(),
mongoc_database_set_read_prefs(), or
mongoc_database_set_read_concern(), and want to preserve an unaltered
copy of the struct.
RETURNS
A newly allocated mongoc_database_t that should be freed with
mongoc_database_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_DATABASE_COPY(3)
mongoc_database_create_collection.3
MONGOC_DATABASE_CREATE_COLLECTION(3)ibmongocNGOC_DATABASE_CREATE_COLLECTION(3)
SYNOPSIS
mongoc_collection_t *
mongoc_database_create_collection (mongoc_database_t *database,
const char *name,
const bson_t *opts,
bson_error_t *error);
PARAMETERS
+ database: A mongoc_database_t.
+ name: The name of the new collection.
+ opts: An optional bson_t for opts to the create command.
+ error: A location for a bson_error_t or NULL.
DESCRIPTION
This function creates a mongoc_collection_t from the given
mongoc_database_t.
If no write concern is provided in opts, the database's write concern
is used.
The encryptedFields document in opts may be used to create a collection
used for Queryable Encryption.
For a list of all options, see the MongoDB Manual entry on the create
command.
ERRORS
Errors are propagated via the error parameter.
RETURNS
This function returns a newly allocated mongoc_collection_t upon suc-
cess, NULL upon failure and error is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_DATABASE_CREATE_COLLECTION(3)
mongoc_database_destroy.3
MONGOC_DATABASE_DESTROY(3) libmongoc MONGOC_DATABASE_DESTROY(3)
SYNOPSIS
void
mongoc_database_destroy (mongoc_database_t *database);
Releases all resources associated with database, including freeing the
structure. Does nothing if database is NULL.
PARAMETERS
+ database: A mongoc_database_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_DATABASE_DESTROY(3)
mongoc_database_drop.3
MONGOC_DATABASE_DROP(3) libmongoc MONGOC_DATABASE_DROP(3)
SYNOPSIS
bool
mongoc_database_drop (mongoc_database_t *database, bson_error_t *error);
PARAMETERS
+ database: A mongoc_database_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
For more information, see mongoc_database_drop_with_opts(). This func-
tion is a thin wrapper, passing NULL in as bson_t parameter.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_DATABASE_DROP(3)
mongoc_database_drop_with_opts.3
MONGOC_DATABASE_DROP_WITH_OPTS(3) libmongoc MONGOC_DATABASE_DROP_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_database_drop_with_opts (mongoc_database_t *database,
const bson_t *opts,
bson_error_t *error);
PARAMETERS
+ database: A mongoc_database_t.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
database, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
DESCRIPTION
This function attempts to drop a database on the MongoDB server.
If no write concern is provided in opts, the database's write concern
is used.
The encryptedFields document in opts may be used to drop a collection
used for Queryable Encryption.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_DATABASE_DROP_WITH_OPTS(3)
mongoc_database_find_collections_with_opts.3
MONGOC_DATABASE_FIND_COLLECTIONS_WITHbOPTS(3)ASE_FIND_COLLECTIONS_WITH_OPTS(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_database_find_collections_with_opts (mongoc_database_t *database,
const bson_t *opts);
Fetches a cursor containing documents, each corresponding to a collec-
tion on this database.
To get collection names only, use
mongoc_database_get_collection_names_with_opts().
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
PARAMETERS
+ database: A mongoc_database_t.
+ opts: A bson_t containing additional options.
opts may be NULL or a BSON document with additional command options:
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
database, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
For a list of all options, see the MongoDB Manual entry on the listCol-
lections command.
ERRORS
Use mongoc_cursor_error() on the returned cursor to check for errors.
RETURNS
This function returns a newly allocated mongoc_cursor_t that should be
freed with mongoc_cursor_destroy() when no longer in use. The returned
mongoc_cursor_t is never NULL, even on error. The user must call
mongoc_cursor_next() on the returned mongoc_cursor_t to execute the
initial command.
Cursor errors can be checked with mongoc_cursor_error_document(). It
always fills out the bson_error_t if an error occurred, and optionally
includes a server reply document if the error occurred server-side.
WARNING:
Failure to handle the result of this function is a programming er-
ror.
In the returned cursor each result corresponds to the server's repre-
sentation of a collection in this database.
The cursor functions mongoc_cursor_set_limit(),
mongoc_cursor_set_batch_size(), and
mongoc_cursor_set_max_await_time_ms() have no use on the returned cur-
sor.
EXAMPLES
{
bson_t opts = BSON_INITIALIZER;
bson_t name_filter;
const bson_t *doc;
bson_iter_t iter;
bson_error_t error;
mongoc_cursor_t *cursor;
BSON_APPEND_DOCUMENT_BEGIN (&opts, "filter", &name_filter);
/* find collections with names like "abbbbc" */
BSON_APPEND_REGEX (&name_filter, "name", "ab+c", NULL);
bson_append_document_end (&opts, &name_filter);
cursor = mongoc_database_find_collections_with_opts (database, &opts);
while (mongoc_cursor_next (cursor, &doc)) {
bson_iter_init_find (&iter, doc, "name");
printf ("found collection: %s\n", bson_iter_utf8 (&iter, NULL));
}
if (mongoc_cursor_error (cursor, &error)) {
fprintf (stderr, "%s\n", error.message);
}
mongoc_cursor_destroy (cursor);
bson_destroy (&opts);
}
SEE ALSO:
mongoc_database_get_collection_names_with_opts()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,D2025ASE_FIND_COLLECTIONS_WITH_OPTS(3)
mongoc_database_get_collection.3
MONGOC_DATABASE_GET_COLLECTION(3) libmongoc MONGOC_DATABASE_GET_COLLECTION(3)
SYNOPSIS
mongoc_collection_t *
mongoc_database_get_collection (mongoc_database_t *database,
const char *name);
Allocates a new mongoc_collection_t structure for the collection named
name in database.
RETURNS
A newly allocated mongoc_collection_t that should be freed with
mongoc_collection_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_DATABASE_GET_COLLECTION(3)
mongoc_database_get_collection_names_with_opts.3
MONGOC_DATABASE_GET_COLLECTIONONAMESiWITHgOPTS(3)COLLECTION_NAMES_WITH_OPTS(3)
SYNOPSIS
char **
mongoc_database_get_collection_names_with_opts (mongoc_database_t *database,
const bson_t *opts,
bson_error_t *error);
Fetches a NULL terminated array of NULL-byte terminated char* strings
containing the names of all of the collections in database.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
PARAMETERS
+ database: A mongoc_database_t.
+ opts: A bson_t containing additional options.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
database, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
For a list of all options, see the MongoDB Manual entry on the listCol-
lections command.
ERRORS
Errors are propagated via the error parameter.
RETURNS
A NULL terminated array of NULL terminated char* strings that should be
freed with bson_strfreev(). Upon failure, NULL is returned and error is
set.
EXAMPLES
{
bson_t opts = BSON_INITIALIZER;
mongoc_read_concern_t *rc;
bson_error_t error;
char **strv;
unsigned i;
rc = mongoc_read_concern_new ();
mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_MAJORITY);
mongoc_read_concern_append (rc, &opts);
if ((strv = mongoc_database_get_collection_names_with_opts (
database, &opts, &error))) {
for (i = 0; strv[i]; i++)
printf ("%s\n", strv[i]);
bson_strfreev (strv);
} else {
fprintf (stderr, "Command failed: %s\n", error.message);
}
mongoc_read_concern_destroy (rc);
bson_destroy (&opts);
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayD12,B2025GET_COLLECTION_NAMES_WITH_OPTS(3)
mongoc_database_get_name.3
MONGOC_DATABASE_GET_NAME(3) libmongoc MONGOC_DATABASE_GET_NAME(3)
SYNOPSIS
const char *
mongoc_database_get_name (mongoc_database_t *database);
Fetches the name of the database.
PARAMETERS
+ database: A mongoc_database_t.
RETURNS
A string which should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_DATABASE_GET_NAME(3)
mongoc_database_get_read_concern.3
MONGOC_DATABASE_GET_READ_CONCERN(3)libmongocONGOC_DATABASE_GET_READ_CONCERN(3)
SYNOPSIS
const mongoc_read_concern_t *
mongoc_database_get_read_concern (const mongoc_database_t *database);
This function retrieves the default mongoc_read_concern_t to use with
database as configured by the client.
PARAMETERS
+ database: A mongoc_database_t.
RETURNS
A mongoc_read_concern_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_DATABASE_GET_READ_CONCERN(3)
mongoc_database_get_read_prefs.3
MONGOC_DATABASE_GET_READ_PREFS(3) libmongoc MONGOC_DATABASE_GET_READ_PREFS(3)
SYNOPSIS
const mongoc_read_prefs_t *
mongoc_database_get_read_prefs (const mongoc_database_t *database);
Fetches the default read preferences to use with database.
PARAMETERS
+ database: A mongoc_database_t.
RETURNS
A mongoc_write_concern_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_DATABASE_GET_READ_PREFS(3)
mongoc_database_get_write_concern.3
MONGOC_DATABASE_GET_WRITE_CONCERN(3)ibmongocNGOC_DATABASE_GET_WRITE_CONCERN(3)
SYNOPSIS
const mongoc_write_concern_t *
mongoc_database_get_write_concern (const mongoc_database_t *database);
This function retrieves the default mongoc_write_concern_t to use with
database as configured by the client.
PARAMETERS
+ database: A mongoc_database_t.
RETURNS
A mongoc_write_concern_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_DATABASE_GET_WRITE_CONCERN(3)
mongoc_database_has_collection.3
MONGOC_DATABASE_HAS_COLLECTION(3) libmongoc MONGOC_DATABASE_HAS_COLLECTION(3)
SYNOPSIS
bool
mongoc_database_has_collection (mongoc_database_t *database,
const char *name,
bson_error_t *error);
This function checks to see if a collection exists on the MongoDB
server within database.
PARAMETERS
+ database: A mongoc_database_t.
+ name: A string containing the name of the collection.
+ error: An optional location for a bson_error_t or NULL.
ERRORS
Errors are propagated via the error parameter.
RETURNS
If the function succeeds, it returns true if the collection exists and
false if not, and in either case the fields of error are cleared, if
error is not NULL.
Returns false and sets error if there are invalid arguments or a server
or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_DATABASE_HAS_COLLECTION(3)
mongoc_database_read_command_with_opts.3
MONGOC_DATABASE_READ_COMMAND_WITH_OPTS(3)gocDATABASE_READ_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_database_read_command_with_opts (mongoc_database_t *database,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, applying logic that is specific to
commands that read, and taking the MongoDB server version into account.
To send a raw command to the server without any of this logic, use
mongoc_database_command_simple().
Use this function for commands that read such as "count" or "distinct".
Read preferences, read concern, and collation can be overridden by var-
ious sources. In a transaction, read concern and write concern are pro-
hibited in opts and the read preference must be primary or NULL. The
highest-priority sources for these options are listed first in the fol-
lowing table. No write concern is applied.
+-----------------+--------------+-----------+
|Read Preferences | Read Concern | Collation |
+-----------------+--------------+-----------+
|read_prefs | opts | opts |
+-----------------+--------------+-----------+
|Transaction | Transaction | |
+-----------------+--------------+-----------+
|database | | |
+-----------------+--------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
reply is always initialized, and must be freed with bson_destroy().
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
Retry logic occurs regardless of the underlying command. Retrying
mapReduce has the potential for degraded performance. Retrying a get-
More command has the potential to miss results. For those commands, use
generic command helpers (like mongoc_database_command_with_opts()) in-
stead.
PARAMETERS
+ database: A mongoc_database_t.
+ command: A bson_t containing the command specification.
+ read_prefs: An optional mongoc_read_prefs_t.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
database, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025ATABASE_READ_COMMAND_WITH_OPTS(3)
mongoc_database_read_write_command_with_opts.3
MONGOC_DATABASE_READ_WRITE_COMMANDGWITHoOPTS(3)READ_WRITE_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_database_read_write_command_with_opts (
mongoc_database_t *database,
const bson_t *command,
const mongoc_read_prefs_t *read_prefs /* UNUSED */,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, applying logic for commands that both
read and write, and taking the MongoDB server version into account. To
send a raw command to the server without any of this logic, use
mongoc_database_command_simple().
Use this function for commands that both read and write, such as
"mapReduce" with an output collection.
Read and write concern and collation can be overridden by various
sources. In a transaction, read concern and write concern are prohib-
ited in opts. The highest-priority sources for these options are listed
first in the following table. Read preferences are not applied. The
write concern is omitted for MongoDB before 3.4.
+-------------+---------------+-----------+
|Read Concern | Write Concern | Collation |
+-------------+---------------+-----------+
|opts | opts | opts |
+-------------+---------------+-----------+
|Transaction | Transaction | |
+-------------+---------------+-----------+
|database | database | |
+-------------+---------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
reply is always initialized, and must be freed with bson_destroy().
(The mongoc_read_prefs_t parameter was included by mistake when this
function was introduced in libmongoc 1.5. A command that writes must
not obey a read preference.)
PARAMETERS
+ database: A mongoc_database_t.
+ command: A bson_t containing the command specification.
+ read_prefs: Ignored.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
database, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MOMayC12,T2025E_READ_WRITE_COMMAND_WITH_OPTS(3)
mongoc_database_remove_all_users.3
MONGOC_DATABASE_REMOVE_ALL_USERS(3)libmongocONGOC_DATABASE_REMOVE_ALL_USERS(3)
SYNOPSIS
bool
mongoc_database_remove_all_users (mongoc_database_t *database,
bson_error_t *error);
This function will remove all users configured to access database.
PARAMETERS
+ database: A mongoc_database_t.
+ error: An optional location for a bson_error_t or NULL.
ERRORS
Errors are propagated via the error parameter. This may fail if there
are socket errors or the current user is not authorized to perform the
given command.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_DATABASE_REMOVE_ALL_USERS(3)
mongoc_database_remove_user.3
MONGOC_DATABASE_REMOVE_USER(3) libmongoc MONGOC_DATABASE_REMOVE_USER(3)
SYNOPSIS
bool
mongoc_database_remove_user (mongoc_database_t *database,
const char *username,
bson_error_t *error);
This function removes the user named username from database.
PARAMETERS
+ database: A mongoc_database_t.
+ username: A string containing the username of the user to remove.
+ error: An optional location for a bson_error_t or NULL.
ERRORS
Errors are propagated via the error parameter. This could include
socket errors or others if the current user is not authorized to per-
form the command.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_DATABASE_REMOVE_USER(3)
mongoc_database_set_read_concern.3
MONGOC_DATABASE_SET_READ_CONCERN(3)libmongocONGOC_DATABASE_SET_READ_CONCERN(3)
SYNOPSIS
void
mongoc_database_set_read_concern (mongoc_database_t *database,
const mongoc_read_concern_t *read_concern);
This function sets the read concern to use on operations performed with
database. Collections created with mongoc_database_get_collection() af-
ter this call will inherit this read concern.
The default read concern is empty: No readConcern is sent to the server
unless explicitly configured.
PARAMETERS
+ database: A mongoc_database_t.
+ read_concern: A mongoc_read_concern_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_DATABASE_SET_READ_CONCERN(3)
mongoc_database_set_read_prefs.3
MONGOC_DATABASE_SET_READ_PREFS(3) libmongoc MONGOC_DATABASE_SET_READ_PREFS(3)
SYNOPSIS
void
mongoc_database_set_read_prefs (mongoc_database_t *database,
const mongoc_read_prefs_t *read_prefs);
This function sets the default read preferences to use on operations
performed with database. Collections created with
mongoc_database_get_collection() after this call will inherit these
read preferences.
The global default is MONGOC_READ_PRIMARY: if the client is connected
to a replica set it reads from the primary, otherwise it reads from the
current MongoDB server.
Please see the MongoDB website for a description of Read Preferences.
PARAMETERS
+ database: A mongoc_database_t.
+ read_prefs: A mongoc_read_prefs_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_DATABASE_SET_READ_PREFS(3)
mongoc_database_set_write_concern.3
MONGOC_DATABASE_SET_WRITE_CONCERN(3)ibmongocNGOC_DATABASE_SET_WRITE_CONCERN(3)
SYNOPSIS
void
mongoc_database_set_write_concern (mongoc_database_t *database,
const mongoc_write_concern_t *write_concern);
This function sets the write concern to use on operations performed
with database. Collections created with
mongoc_database_get_collection() after this call will inherit this
write concern.
The default write concern is MONGOC_WRITE_CONCERN_W_DEFAULT: the driver
blocks awaiting basic acknowledgement of write operations from MongoDB.
This is the correct write concern for the great majority of applica-
tions.
PARAMETERS
+ database: A mongoc_database_t.
+ write_concern: A mongoc_write_concern_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_DATABASE_SET_WRITE_CONCERN(3)
mongoc_database_t.3
MONGOC_DATABASE_T(3) libmongoc MONGOC_DATABASE_T(3)
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().
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;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_DATABASE_T(3)
mongoc_database_watch.3
MONGOC_DATABASE_WATCH(3) libmongoc MONGOC_DATABASE_WATCH(3)
SYNOPSIS
mongoc_change_stream_t*
mongoc_database_watch (const mongoc_database_t *db,
const bson_t *pipeline,
const bson_t *opts);
A helper function to create a change stream. It is preferred to call
this function over using a raw aggregation to create a change stream.
This function uses the read preference and read concern of the data-
base. If the change stream needs to re-establish connection, the same
read preference will be used. This may happen if the change stream en-
counters a resumable error.
WARNING:
A change stream is only supported with majority read concern.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
PARAMETERS
+ db: A mongoc_database_t specifying the database which the change
stream listens to.
+ pipeline: A bson_t representing an aggregation pipeline appended to
the change stream. This may be an empty document.
+ opts: A bson_t containing change stream options.
Changed in version 2.0.0: batchSize of 0 is applied to the aggregate
command. 0 was previously ignored.
opts may be NULL or a BSON document with additional command options:
+ batchSize: An int32 requesting a limit of documents returned in each
server reply. If positive, the batchSize is applied to both aggregate
and getMore commands. If 0, the batchSize is only applied to the ag-
gregate command (Useful to request an immediate cursor without sig-
nificant server-side work. See Aggregate Data Specifying Batch Size).
If omitted or negative, the value is ignored and server defaults are
used (See Cursor Batches for a description of server defaults).
+ resumeAfter: A Document representing the logical starting point of
the change stream. The result of
mongoc_change_stream_get_resume_token() or the _id field of any
change received from a change stream can be used here. This option is
mutually exclusive with startAfter and startAtOperationTime.
+ startAfter: A Document representing the logical starting point of the
change stream. Unlike resumeAfter, this can resume notifications af-
ter an "invalidate" event. The result of
mongoc_change_stream_get_resume_token() or the _id field of any
change received from a change stream can be used here. This option
is mutually exclusive with resumeAfter and startAtOperationTime.
+ startAtOperationTime: A Timestamp. The change stream only provides
changes that occurred at or after the specified timestamp. Any com-
mand run against the server will return an operation time that can be
used here. This option is mutually exclusive with resumeAfter and
startAfter.
+ maxAwaitTimeMS: An int64 representing the maximum amount of time a
call to mongoc_change_stream_next() will block waiting for data
+ fullDocument: An optional UTF-8 string. Set this option to "default",
"updateLookup", "whenAvailable", or "required", If unset, The string
"default" is assumed. Set this option to "updateLookup" to direct the
change stream cursor to lookup the most current majority-committed
version of the document associated to an update change stream event.
+ fullDocumentBeforeChange: An optional UTF-8 string. Set this option
to "whenAvailable", "required", or "off". When unset, the default
value is "off". Similar to "fullDocument", but returns the value of
the document before the associated change.
+ showExpandedEvents: Set to true to return an expanded list of change
stream events. Available only on MongoDB versions >=6.0
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Only string values are supported prior to MongoDB
4.4.
RETURNS
A newly allocated mongoc_change_stream_t which must be freed with
mongoc_change_stream_destroy() when no longer in use. The returned
mongoc_change_stream_t is never NULL. If there is an error, it can be
retrieved with mongoc_change_stream_error_document(), and subsequent
calls to mongoc_change_stream_next() will return false.
SEE ALSO:
mongoc_client_watch()
mongoc_collection_watch()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_DATABASE_WATCH(3)
mongoc_database_write_command_with_opts.3
MONGOC_DATABASE_WRITE_COMMAND_WITH_OPTS(3)ocATABASE_WRITE_COMMAND_WITH_OPTS(3)
SYNOPSIS
bool
mongoc_database_write_command_with_opts (mongoc_database_t *database,
const bson_t *command,
const bson_t *opts,
bson_t *reply,
bson_error_t *error);
Execute a command on the server, applying logic that is specific to
commands that write, and taking the MongoDB server version into ac-
count. To send a raw command to the server without any of this logic,
use mongoc_database_command_simple().
Use this function for commands that write such as "drop" or "create-
Role" (but not for "insert", "update", or "delete", see Basic Write Op-
erations). Write concern and collation can be overridden by various
sources. In a transaction, read concern and write concern are prohib-
ited in opts. The highest-priority sources for these options are listed
first in the following table. The write concern is omitted for MongoDB
before 3.4.
+--------------+-----------+
|Write Concern | Collation |
+--------------+-----------+
|opts | opts |
+--------------+-----------+
|Transaction | |
+--------------+-----------+
|database | |
+--------------+-----------+
See the example for transactions and for the "distinct" command with
opts.
reply is always initialized, and must be freed with bson_destroy().
PARAMETERS
+ database: A mongoc_database_t.
+ db_name: The name of the database to run the command on.
+ command: A bson_t containing the command specification.
+ opts: A bson_t containing additional options.
+ reply: A maybe-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ error: An optional location for a bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
database, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ collation: Configure textual comparisons. See Setting Collation Or-
der, and the MongoDB Manual entry on Collation. Collation requires
MongoDB 3.2 or later, otherwise an error is returned.
+ serverId: To target a specific server, include an int32 "serverId"
field. Obtain the id by calling mongoc_client_select_server(), then
mongoc_server_description_id() on its return value.
Consult the MongoDB Manual entry on Database Commands for each com-
mand's arguments.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
A write concern timeout or write concern error is considered a failure.
BASIC WRITE OPERATIONS
Do not use this function to call the basic write commands "insert",
"update", and "delete". Those commands require special logic not imple-
mented in mongoc_database_write_command_with_opts. For basic write op-
erations use CRUD functions such as mongoc_collection_insert_one() and
the others described in the CRUD tutorial, or use the Bulk API.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025TABASE_WRITE_COMMAND_WITH_OPTS(3)
mongoc_error_has_label.3
MONGOC_ERROR_HAS_LABEL(3) libmongoc MONGOC_ERROR_HAS_LABEL(3)
SYNOPSIS
bool
mongoc_error_has_label (const bson_t *reply, const char *label);
Test whether a reply from a failed operation includes a specific error
label. See Error Labels for details, and see
mongoc_client_session_start_transaction() for example code that demon-
strates their use.
PARAMETERS
+ reply: A non-NULL pointer to overwritable storage for a bson_t to
contain the results.
+ label: The label to test for, such as "TransientTransactionError" or
"UnknownTransactionCommitResult".
RETURNS
Returns true if reply contains the error label.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_ERROR_HAS_LABEL(3)
mongoc_errors.3
MONGOC_ERRORS(3) libmongoc MONGOC_ERRORS(3)
<< libmongoc - API
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 er-
ror, and code for the specific error. message is a human-readable error
description.
SEE ALSO:
Handling Errors in libbson.
+--------------------+----------------------------------+--------------------------------------------+
|Code | Description | |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_CLIENT | MONGOC_ER- | You tried to send a |
| | ROR_CLIENT_TOO_BIG | message larger than |
| | | the server's max |
| | | message size. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Wrong credentials, |
| | ROR_CLIENT_AUTHEN- | or failure sending |
| | TICATE | or receiving au- |
| | | thentication mes- |
| | | sages. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | You tried an TLS |
| | ROR_CLIENT_NO_AC- | connection but the |
| | CEPTABLE_PEER | driver was not |
| | | built with TLS. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | You began iterating |
| | ROR_CLIENT_IN_EX- | an exhaust cursor, |
| | HAUST | then tried to begin |
| | | another operation |
| | | with the same |
| | | mongoc_client_t. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Failure related to |
| | ROR_CLIENT_SES- | creating or using a |
| | SION_FAILURE | logical session. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Failure related to |
| | ROR_CLIENT_IN- | arguments passed |
| | VALID_ENCRYP- | when initializing |
| | TION_ARG | In-Use Encryption. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Failure related to |
| | ROR_CLIENT_IN- | In-Use Encryption. |
| | VALID_ENCRYP- | |
| | TION_STATE | |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | You attempted to |
| | ROR_CLIENT_IN- | connect to a Mon- |
| | VALID_LOAD_BALANCER | goDB server behind |
| | | a load balancer, |
| | | but the server does |
| | | not advertize load |
| | | balanced support. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | You attempted to |
| | ROR_CLIENT_NOT_READY | create a client but |
| | | did not previously |
| | | call mongoc_init() |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_STREAM | MONGOC_ER- | DNS failure. |
| | ROR_STREAM_NAME_RES- | |
| | OLUTION | |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Timeout communicat- |
| | ROR_STREAM_SOCKET | ing with server, or |
| | | connection closed. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Failed to connect |
| | ROR_STREAM_CONNECT | to server. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_PROTO- | MONGOC_ERROR_PROTO- | Corrupt response |
|COL | COL_INVALID_REPLY | from server. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_PROTO- | The server version |
| | COL_BAD_WIRE_VERSION | is too old or too |
| | | new to communicate |
| | | with the driver. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_CURSOR | MONGOC_ERROR_CUR- | You passed bad ar- |
| | SOR_INVALID_CURSOR | guments 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_ER- | A resume token was not returned in |
| | ROR_CHANGE_STREAM_NO_RE- | a document found with |
| | SUME_TOKEN | mongoc_change_stream_next() |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_QUERY | MONGOC_ERROR_QUERY_FAIL- | Error API Version 1: Server error |
| | URE | from command or query. The server |
| | | error message is in message. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_SERVER | MONGOC_ERROR_QUERY_FAIL- | Error API Version 2: Server error |
| | URE | 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_IN- | You passed an invalid or oversized |
| | VALID | BSON document as a parameter or the |
| | | server reply was corrupt. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_NAME- | MONGOC_ERROR_NAME- | You tried to create a collection |
|SPACE | SPACE_INVALID | with an invalid name. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_COM- | MONGOC_ERROR_COMMAND_IN- | Many functions set this error code |
|MAND | VALID_ARG | when passed bad parameters. Print |
| | | the error message for details. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_PROTO- | You tried to use a command option |
| | COL_BAD_WIRE_VERSION | the server does not support. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_DUPLI- | An insert or update failed because |
| | CATE_KEY | because of a duplicate _id or other |
| | | unique-index violation. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | The operation failed because max- |
| | ROR_MAX_TIME_MS_EXPIRED | TimeMS expired. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_SERVER_SE- | The serverId option for an opera- |
| | LECTION_INVALID_ID | tion conflicts with the pinned |
| | | server for that operation's client |
| | | session (denoted by the sessionId |
| | | option). |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_COM- | Error code from server. | Error API Version 1: Server error |
|MAND | | 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_COL- | MONGOC_ERROR_COLLEC- | Invalid or empty input to |
|LECTION | TION_INSERT_FAILED, MON- | mongoc_collection_insert_one(), |
| | GOC_ERROR_COLLECTION_UP- | mongoc_collection_insert_many(), |
| | DATE_FAILED, MONGOC_ER- | mongoc_collection_update_one(), |
| | ROR_COLLEC- | mongoc_collection_update_many(), |
| | TION_DELETE_FAILED. | mongoc_collection_replace_one(), |
| | | mongoc_collection_delete_one(), or |
| | | mongoc_collection_delete_many(). |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_COL- | Error code from server. | Error API Version 1: Server error |
|LECTION | | 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(), |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_GRIDFS | MONGOC_ER- | The GridFS file is missing a docu- |
| | ROR_GRIDFS_CHUNK_MISSING | ment in its chunks collection. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_GRIDFS_COR- | A data inconsistency was detected |
| | RUPT | in GridFS. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_GRIDFS_IN- | You passed a NULL filename to |
| | VALID_FILENAME | mongoc_gridfs_remove_by_filename(). |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_GRIDFS_PRO- | You called |
| | TOCOL_ERROR | mongoc_gridfs_file_set_id() after |
| | | mongoc_gridfs_file_save(), or tried |
| | | to write on a closed GridFS stream. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | A GridFS file is missing from files |
| | ROR_GRIDFS_BUCKET_FILE_NOT_FOUND | collection. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | An error occurred on a stream cre- |
| | ROR_GRIDFS_BUCKET_STREAM | ated from a GridFS operation like |
| | | mongoc_gridfs_bucket_upload_from_stream(). |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_SCRAM | MONGOC_ERROR_SCRAM_PROTOCOL_ER- | Failure in SCRAM-SHA-1 or SCRAM-SHA-256 |
| | ROR | authentication. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ER- | MONGOC_ERROR_SERVER_SELEC- | No replica set member or mongos is avail- |
|ROR_SERVER_SELEC- | TION_FAILURE | able, or none matches your read prefer- |
|TION | | ence, or you supplied an invalid |
| | | mongoc_read_prefs_t. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ER- | Error code from server. | There was a write concern error or timeout |
|ROR_WRITE_CONCERN | | from the server. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_TRANS- | MONGOC_ERROR_TRANSACTION_INVALID | You attempted to start a transaction when |
|ACTION | | one is already in progress, or commit or |
| | | abort when there is no transaction. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ER- | Error code produced by libmon- | An error occurred in the library responsi- |
|ROR_CLIENT_SIDE_EN- | gocrypt. | ble for In-Use Encryption |
|CRYPTION | | |
+--------------------+----------------------------------+--------------------------------------------+
|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 |
+--------------------+----------------------------------+--------------------------------------------+
|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 |
+--------------------+----------------------------------+--------------------------------------------+
ERROR LABELS
In some cases your application must make decisions based on what cate-
gory of error the driver has returned, but these categories do not cor-
respond perfectly to an error domain or code. In such cases, error la-
bels provide a reliable way to determine how your application should
respond to an error.
Any C Driver function that has a bson_t out-parameter named reply may
include error labels to the reply, in the form of a BSON field named
"errorLabels" containing an array of strings:
{ "errorLabels": [ "TransientTransactionError" ] }
Use mongoc_error_has_label() to test if a reply contains a specific la-
bel. See mongoc_client_session_start_transaction() for example code
that demonstrates the use of error labels in application logic.
The following error labels are currently defined. Future versions of
MongoDB may introduce new labels.
TransientTransactionError
Within a multi-document transaction, certain errors can leave the
transaction in an unknown or aborted state. These include write con-
flicts, primary stepdowns, and network errors. In response, the appli-
cation should abort the transaction and try the same sequence of opera-
tions again in a new transaction.
UnknownTransactionCommitResult
When mongoc_client_session_commit_transaction() encounters a network
error or certain server errors, it is not known whether the transaction
was committed. Applications should attempt to commit the transaction
again until: the commit succeeds, the commit fails with an error not
labeled "UnknownTransactionCommitResult", or the application chooses to
give up.
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_ER-
ROR_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_one() 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_COLLEC-
TION_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 do-
main, MONGOC_ERROR_SERVER. In Version 2, error codes originating on the
server always have error domain MONGOC_ERROR_SERVER or MONGOC_ER-
ROR_WRITE_CONCERN. When the driver uses Version 2 the application can
always determine the origin and meaning of error codes. New applica-
tions 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_with_opts(), | MONGOC_ERROR_QUERY | MONGOC_ERROR_SERVER |
|mongoc_database_command_with_opts(), | | |
|and other command | | |
|functions | | |
+---------------------------------------------+--------------------+---------------------+
|mongoc_client_get_database_names_with_opts() | MONGOC_ERROR_QUERY | MONGOC_ERROR_SERVER |
|and other command helper functions | | |
+---------------------------------------------+--------------------+---------------------+
|mongoc_collection_insert_one() | MONGOC_ERROR_COM- | MONGOC_ERROR_SERVER |
|mongoc_collection_insert_many() | MAND | |
|mongoc_collection_update_one() | | |
|mongoc_collection_update_many() | | |
|mongoc_collection_replace_one() | | |
|mongoc_collection_delete_one() | | |
|mongoc_collection_delete_many() | | |
+---------------------------------------------+--------------------+---------------------+
|mongoc_bulk_operation_execute() | MONGOC_ERROR_COM- | MONGOC_ERROR_SERVER |
| | MAND | |
+---------------------------------------------+--------------------+---------------------+
|Write-concern timeout | MONGOC_ER- | MONGOC_ER- |
| | ROR_WRITE_CONCERN | ROR_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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_ERRORS(3)
mongoc_find_and_modify_opts_append.3
MONGOC_FIND_AND_MODIFY_OPTS_APPEND(3)bmongocGOC_FIND_AND_MODIFY_OPTS_APPEND(3)
SYNOPSIS
bool
mongoc_find_and_modify_opts_append (mongoc_find_and_modify_opts_t *opts,
const bson_t *extra);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ extra: A bson_t with fields and values to append directly to the fin-
dAndModify command sent to the server.
DESCRIPTION
Adds arbitrary options to the findAndModify command.
extra does not have to remain valid after calling this function.
extra may be NULL or a BSON document with additional command options:
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ sessionId: First, construct a mongoc_client_session_t with
mongoc_client_start_session(). You can begin a transaction with
mongoc_client_session_start_transaction(), optionally with a
mongoc_transaction_opt_t that overrides the options inherited from
collection, and use mongoc_client_session_append() to add the session
to opts. See the example code for mongoc_client_session_t.
+ hint: A document or string that specifies the index to use to support
the query predicate.
+ let: A BSON document consisting of any number of parameter names,
each followed by definitions of constants in the MQL Aggregate Ex-
pression language.
+ comment: A bson_value_t specifying the comment to attach to this com-
mand. The comment will appear in log messages, profiler output, and
currentOp output. Requires MongoDB 4.4 or later.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and logs an error.
APPENDING OPTIONS TO FINDANDMODIFY
opts.c
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);
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_FIND_AND_MODIFY_OPTS_APPEND(3)
mongoc_find_and_modify_opts_destroy.3
MONGOC_FIND_AND_MODIFY_OPTS_DESTROY(3)mongocOC_FIND_AND_MODIFY_OPTS_DESTROY(3)
SYNOPSIS
void
mongoc_find_and_modify_opts_destroy (
mongoc_find_and_modify_opts_t *find_and_modify_opts);
PARAMETERS
+ find_and_modify_opts: A mongoc_find_and_modify_opts_t.
DESCRIPTION
Frees all resources associated with the find and modify builder struc-
ture. Does nothing if find_and_modify_opts is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_FIND_AND_MODIFY_OPTS_DESTROY(3)
mongoc_find_and_modify_opts_get_bypass_document_validation.3
MONGOC_FIND_AND_MODIFYCOPTSDGETDBYPASSmDOCUMENTTVALIDATION(3)ENT_VALIDATION(3)
SYNOPSIS
bool
mongoc_find_and_modify_opts_get_bypass_document_validation (
const mongoc_find_and_modify_opts_t *opts);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
RETURNS
Returns true if
mongoc_find_and_modify_opts_set_bypass_document_validation() was called
previously on opts.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_FIND_AND_MayI12,O2025GET_BYPASS_DOCUMENT_VALIDATION(3)
mongoc_find_and_modify_opts_get_fields.3
MONGOC_FIND_AND_MODIFY_OPTS_GET_FIELDS(3)gocFIND_AND_MODIFY_OPTS_GET_FIELDS(3)
SYNOPSIS
void
mongoc_find_and_modify_opts_get_fields (
const mongoc_find_and_modify_opts_t *opts, bson_t *fields);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ fields: An uninitialized bson_t.
DESCRIPTION
Copy to fields the BSON document that was set with
mongoc_find_and_modify_opts_set_fields(), or initializes fields with an
empty BSON document.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025IND_AND_MODIFY_OPTS_GET_FIELDS(3)
mongoc_find_and_modify_opts_get_flags.3
MONGOC_FIND_AND_MODIFY_OPTS_GET_FLAGS(3)ngoc_FIND_AND_MODIFY_OPTS_GET_FLAGS(3)
SYNOPSIS
mongoc_find_and_modify_flags_t
mongoc_find_and_modify_opts_get_flags (
const mongoc_find_and_modify_opts_t *opts);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
RETURNS
Returns the flags set with mongoc_find_and_modify_opts_set_flags().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025FIND_AND_MODIFY_OPTS_GET_FLAGS(3)
mongoc_find_and_modify_opts_get_max_time_ms.3
MONGOC_FIND_AND_MODIFY_OPTS_GET_MAXlTIMEnMS(3)D_MODIFY_OPTS_GET_MAX_TIME_MS(3)
SYNOPSIS
uint32_t
mongoc_find_and_modify_opts_get_max_time_ms (
const mongoc_find_and_modify_opts_t *opts);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
RETURNS
Returns the "maxTimeMS" value set with
mongoc_find_and_modify_opts_set_max_time_ms().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,I2025ND_MODIFY_OPTS_GET_MAX_TIME_MS(3)
mongoc_find_and_modify_opts_get_sort.3
MONGOC_FIND_AND_MODIFY_OPTS_GET_SORT(3)ongocC_FIND_AND_MODIFY_OPTS_GET_SORT(3)
SYNOPSIS
void
mongoc_find_and_modify_opts_get_sort (const mongoc_find_and_modify_opts_t *opts,
bson_t *sort);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ sort: An uninitialized bson_t.
DESCRIPTION
Copies the sort document set with
mongoc_find_and_modify_opts_set_sort(), or initializes sort with an
empty BSON document.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_FIND_AND_MODIFY_OPTS_GET_SORT(3)
mongoc_find_and_modify_opts_get_update.3
MONGOC_FIND_AND_MODIFY_OPTS_GET_UPDATE(3)gocFIND_AND_MODIFY_OPTS_GET_UPDATE(3)
SYNOPSIS
void
mongoc_find_and_modify_opts_get_update (
const mongoc_find_and_modify_opts_t *opts, bson_t *update);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ update: An uninitialized bson_t.
DESCRIPTION
Copies the update document set with
mongoc_find_and_modify_opts_set_update(), or initializes update with an
empty BSON document.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025IND_AND_MODIFY_OPTS_GET_UPDATE(3)
mongoc_find_and_modify_opts_new.3
MONGOC_FIND_AND_MODIFY_OPTS_NEW(3) libmongocMONGOC_FIND_AND_MODIFY_OPTS_NEW(3)
SYNOPSIS
mongoc_find_and_modify_opts_t *
mongoc_find_and_modify_opts_new (void);
RETURNS
Creates a newly allocated find and modify builder structure that is
used to create a findAndModify command. This should be freed with
mongoc_find_and_modify_opts_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_FIND_AND_MODIFY_OPTS_NEW(3)
mongoc_find_and_modify_opts_set_bypass_document_validation.3
MONGOC_FIND_AND_MODIFYCOPTSDSETDBYPASSmDOCUMENTTVALIDATION(3)ENT_VALIDATION(3)
SYNOPSIS
bool
mongoc_find_and_modify_opts_set_bypass_document_validation (
mongoc_find_and_modify_opts_t *opts, bool bypass);
This option is only available when talking to MongoDB 3.2 and later.
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ bypass: If the schema validation rules should be ignored.
DESCRIPTION
Adds bypassDocumentValidation argument to the builder.
When authentication is enabled, the authenticated user must have either
the "dbadmin" or "restore" roles to bypass document validation.
RETURNS
Returns true if it successfully added the option to the builder, other-
wise false and logs an error.
SETTING BYPASSDOCUMENTVALIDATION
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);
}
Outputs:
{
"lastErrorObject" : {"updatedExisting" : true, "n" : 1},
"value" : {
"_id" : {"$oid" : "56562a99d13e6d86239c7b00"},
"age" : 34,
"firstname" : "Zlatan",
"goals" : 342,
"lastname" : "Ibrahimovic",
"profession" : "Football player",
"position" : "striker"
},
"ok" : 1
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_FIND_AND_MayI12,O2025SET_BYPASS_DOCUMENT_VALIDATION(3)
mongoc_find_and_modify_opts_set_fields.3
MONGOC_FIND_AND_MODIFY_OPTS_SET_FIELDS(3)gocFIND_AND_MODIFY_OPTS_SET_FIELDS(3)
SYNOPSIS
bool
mongoc_find_and_modify_opts_set_fields (mongoc_find_and_modify_opts_t *opts,
const bson_t *fields);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ fields: A subset of fields to return. Choose which fields to include
by appending {fieldname: 1} for each fieldname, or excluding it with
{fieldname: 0}.
DESCRIPTION
Adds fields argument to the builder.
fields does not have to remain valid after calling this function.
RETURNS
Returns true if it successfully added the option to the builder, other-
wise false.
SETTING FIELDS
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);
}
Outputs:
{
"lastErrorObject"
: {"updatedExisting" : true, "n" : 1},
"value"
: {"_id" : {"$oid" : "56562a99d13e6d86239c7b00"}, "goals" : 343},
"ok" : 1
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025IND_AND_MODIFY_OPTS_SET_FIELDS(3)
mongoc_find_and_modify_opts_set_flags.3
MONGOC_FIND_AND_MODIFY_OPTS_SET_FLAGS(3)ngoc_FIND_AND_MODIFY_OPTS_SET_FLAGS(3)
SYNOPSIS
bool
mongoc_find_and_modify_opts_set_flags (
mongoc_find_and_modify_opts_t *opts,
const mongoc_find_and_modify_flags_t flags);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ flags: .
DESCRIPTION
Adds one or more flags to the builder.
+---------------------------+----------------------------+
|MONGOC_FIND_AND_MOD- | Default. Doesn't add any- |
|IFY_NONE | thing to the builder. |
+---------------------------+----------------------------+
|MONGOC_FIND_AND_MODIFY_RE- | Will instruct |
|MOVE | find_and_modify to remove |
| | the matching document. |
+---------------------------+----------------------------+
|MONGOC_FIND_AND_MODIFY_UP- | Update the matching docu- |
|SERT | ment or, if no document |
| | matches, insert the docu- |
| | ment. |
+---------------------------+----------------------------+
|MONGOC_FIND_AND_MODIFY_RE- | Return the resulting docu- |
|TURN_NEW | ment. |
+---------------------------+----------------------------+
RETURNS
Returns Returns true if it successfully added the option to the
builder, otherwise false and logs an error.
SETTING FLAGS
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);
}
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
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025FIND_AND_MODIFY_OPTS_SET_FLAGS(3)
mongoc_find_and_modify_opts_set_max_time_ms.3
MONGOC_FIND_AND_MODIFY_OPTS_SET_MAXlTIMEnMS(3)D_MODIFY_OPTS_SET_MAX_TIME_MS(3)
SYNOPSIS
bool
mongoc_find_and_modify_opts_set_max_time_ms (
mongoc_find_and_modify_opts_t *opts, uint32_t max_time_ms);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ max_time_ms: The maximum server-side execution time permitted, in
milliseconds, or 0 to specify no maximum time (the default setting).
DESCRIPTION
Adds a maxTimeMS argument to the builder.
RETURNS
Returns true if it successfully added the option to the builder, other-
wise false and logs an error.
Note: although max_time_ms is a uint32_t, it is possible to set it as a
uint64_t through the options arguments in some cursor returning func-
tions like mongoc_collection_find_with_opts().
SETTING MAXTIMEMS
opts.c
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);
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,I2025ND_MODIFY_OPTS_SET_MAX_TIME_MS(3)
mongoc_find_and_modify_opts_set_sort.3
MONGOC_FIND_AND_MODIFY_OPTS_SET_SORT(3)ongocC_FIND_AND_MODIFY_OPTS_SET_SORT(3)
SYNOPSIS
bool
mongoc_find_and_modify_opts_set_sort (mongoc_find_and_modify_opts_t *opts,
const bson_t *sort);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ sort: Determines which document the operation modifies if the query
selects multiple documents. findAndModify modifies the first document
in the sort order specified by this argument.
DESCRIPTION
Adds sort argument to the builder.
sort does not have to remain valid after calling this function.
RETURNS
Returns true if it successfully added the option to the builder, other-
wise false.
SETTING SORT
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);
}
Outputs:
{
"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
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_FIND_AND_MODIFY_OPTS_SET_SORT(3)
mongoc_find_and_modify_opts_set_update.3
MONGOC_FIND_AND_MODIFY_OPTS_SET_UPDATE(3)gocFIND_AND_MODIFY_OPTS_SET_UPDATE(3)
SYNOPSIS
bool
mongoc_find_and_modify_opts_set_update (mongoc_find_and_modify_opts_t *opts,
const bson_t *update);
PARAMETERS
+ opts: A mongoc_find_and_modify_opts_t.
+ update: The update document is the same format as the update document
passed to mongoc_collection_update().
DESCRIPTION
Adds update argument to the builder.
update does not have to remain valid after calling this function.
RETURNS
Returns true if it successfully added the option to the builder, other-
wise false.
SETTING UPDATE
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);
}
Outputs:
{
"lastErrorObject" : {"updatedExisting" : true, "n" : 1},
"value" : {
"_id" : {"$oid" : "56562a99d13e6d86239c7b00"},
"age" : 35,
"firstname" : "Zlatan",
"goals" : 342,
"lastname" : "Ibrahimovic",
"profession" : "Football player",
"position" : "striker"
},
"ok" : 1
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025IND_AND_MODIFY_OPTS_SET_UPDATE(3)
mongoc_find_and_modify_opts_t.3
MONGOC_FIND_AND_MODIFY_OPTS_T(3) libmongoc MONGOC_FIND_AND_MODIFY_OPTS_T(3)
find_and_modify abstraction
SYNOPSIS
mongoc_find_and_modify_opts_t is a builder interface to construct the
findAndModify command.
It was created to be able to accommodate new arguments to the findAnd-
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
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);
}
opts.c
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);
}
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: %s\n"
"error message: %s\n",
uri_string,
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;
}
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
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_FIND_AND_MODIFY_OPTS_T(3)
mongoc_get_major_version.3
MONGOC_GET_MAJOR_VERSION(3) libmongoc MONGOC_GET_MAJOR_VERSION(3)
SYNOPSIS
int
mongoc_get_major_version (void);
RETURNS
The value of MONGOC_MAJOR_VERSION when libmongoc was compiled.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GET_MAJOR_VERSION(3)
mongoc_get_micro_version.3
MONGOC_GET_MICRO_VERSION(3) libmongoc MONGOC_GET_MICRO_VERSION(3)
SYNOPSIS
int
mongoc_get_micro_version (void);
RETURNS
The value of MONGOC_MICRO_VERSION when libmongoc was compiled.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GET_MICRO_VERSION(3)
mongoc_get_minor_version.3
MONGOC_GET_MINOR_VERSION(3) libmongoc MONGOC_GET_MINOR_VERSION(3)
SYNOPSIS
int
mongoc_get_minor_version (void);
RETURNS
The value of MONGOC_MINOR_VERSION when libmongoc was compiled.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GET_MINOR_VERSION(3)
mongoc_get_version.3
MONGOC_GET_VERSION(3) libmongoc MONGOC_GET_VERSION(3)
SYNOPSIS
const char *
mongoc_get_version (void);
RETURNS
A string representation of libmongoc's version, formatted something
like "1.2.3" or "1.2.3-pre".
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GET_VERSION(3)
mongoc_gridfs_bucket_abort_upload.3
MONGOC_GRIDFS_BUCKET_ABORT_UPLOAD(3)ibmongocNGOC_GRIDFS_BUCKET_ABORT_UPLOAD(3)
SYNOPSIS
bool
mongoc_gridfs_bucket_abort_upload (mongoc_stream_t *stream);
PARAMETERS
+ stream: A mongoc_stream_t created by
mongoc_gridfs_bucket_open_upload_stream() or
mongoc_gridfs_bucket_open_upload_stream_with_id().
DESCRIPTION
Aborts the upload of a GridFS upload stream.
RETURNS
True on success. False otherwise, and sets an error on stream.
SEE ALSO:
mongoc_gridfs_bucket_open_upload_stream()
mongoc_gridfs_bucket_open_upload_stream_with_id()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_GRIDFS_BUCKET_ABORT_UPLOAD(3)
mongoc_gridfs_bucket_delete_by_id.3
MONGOC_GRIDFS_BUCKET_DELETE_BY_ID(3)ibmongocNGOC_GRIDFS_BUCKET_DELETE_BY_ID(3)
SYNOPSIS
bool
mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket,
const bson_value_t *file_id,
bson_error_t *error);
PARAMETERS
+ bucket: A mongoc_gridfs_bucket_t.
+ file_id: A bson_value_t of the id of the file to delete.
+ error: A bson_error_t to receive any error or NULL.
DESCRIPTION
Deletes a file and its contents from GridFS.
RETURNS
True if the operation succeeded. False otherwise, and sets error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_GRIDFS_BUCKET_DELETE_BY_ID(3)
mongoc_gridfs_bucket_destroy.3
MONGOC_GRIDFS_BUCKET_DESTROY(3) libmongoc MONGOC_GRIDFS_BUCKET_DESTROY(3)
SYNOPSIS
void
mongoc_gridfs_bucket_destroy (mongoc_gridfs_bucket_t *bucket);
PARAMETERS
+ bucket: A mongoc_gridfs_bucket_t or NULL.
DESCRIPTION
Destroys a mongoc_gridfs_bucket_t. Does nothing if passed NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_BUCKET_DESTROY(3)
mongoc_gridfs_bucket_download_to_stream.3
MONGOC_GRIDFS_BUCKET_DOWNLOAD_TO_STREAM(3)ocRIDFS_BUCKET_DOWNLOAD_TO_STREAM(3)
SYNOPSIS
bool
mongoc_gridfs_bucket_download_to_stream (mongoc_gridfs_bucket_t *bucket,
const bson_value_t *file_id,
mongoc_stream_t *destination,
bson_error_t *error);
PARAMETERS
+ bucket: A mongoc_gridfs_bucket_t.
+ file_id: A bson_value_t of the id of the file to download.
+ destination: A mongoc_stream_t which receives data from the down-
loaded file.
+ error: A bson_error_t to receive any error or NULL.
DESCRIPTION
Reads from the GridFS file and writes to the destination stream.
Writes the full contents of the file to the destination stream. The
destination stream is not closed after calling
mongoc_gridfs_bucket_download_to_stream(); call mongoc_stream_close()
after.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
RETURNS
True if the operation succeeded. False otherwise, and sets error.
SEE ALSO:
mongoc_stream_file_new() and mongoc_stream_file_new_for_path(), which can be used to create a destination stream from a file.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025IDFS_BUCKET_DOWNLOAD_TO_STREAM(3)
mongoc_gridfs_bucket_find.3
MONGOC_GRIDFS_BUCKET_FIND(3) libmongoc MONGOC_GRIDFS_BUCKET_FIND(3)
SYNOPSIS
mongoc_cursor_t *
mongoc_gridfs_bucket_find (mongoc_gridfs_bucket_t *bucket,
const bson_t *filter,
const bson_t *opts);
PARAMETERS
+ bucket: A mongoc_gridfs_bucket_t.
+ filter: A bson_t containing the query to execute.
+ opts: A bson_t for query options, supporting all options in
mongoc_collection_find_with_opts() excluding sessionId.
DESCRIPTION
Finds file documents from the bucket's files collection.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
RETURNS
A newly allocated mongoc_cursor_t that must be freed with
mongoc_cursor_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_BUCKET_FIND(3)
mongoc_gridfs_bucket_new.3
MONGOC_GRIDFS_BUCKET_NEW(3) libmongoc MONGOC_GRIDFS_BUCKET_NEW(3)
SYNOPSIS
mongoc_gridfs_bucket_t *
mongoc_gridfs_bucket_new (mongoc_database_t *db,
const bson_t *opts,
const mongoc_read_prefs_t *read_prefs,
bson_error_t* error);
PARAMETERS
+ db: A mongoc_database_t.
+ opts: A bson_t or NULL
+ read_prefs: A mongoc_read_prefs_t used for read operations or NULL to
inherit read preferences from db.
+ error: A bson_error_t or NULL.
opts may be NULL or a BSON document with additional command options:
+ bucketName: A UTF-8 string used as the prefix to the GridFS "chunks"
and "files" collections. Defaults to "fs". The bucket name, together
with the database and suffix collections must not exceed 120 charac-
ters. See the manual for the max namespace length.
+ chunkSizeBytes: An int32 representing the chunk size. Defaults to
255KB.
+ writeConcern: Construct a mongoc_write_concern_t and use
mongoc_write_concern_append() to add the write concern to opts. See
the example code for mongoc_client_write_command_with_opts().
+ readConcern: Construct a mongoc_read_concern_t and use
mongoc_read_concern_append() to add the read concern to opts. See the
example code for mongoc_client_read_command_with_opts(). Read concern
requires MongoDB 3.2 or later, otherwise an error is returned.
DESCRIPTION
Creates a new mongoc_gridfs_bucket_t. Use this handle to perform GridFS
operations.
RETURNS
A newly allocated mongoc_gridfs_bucket_t that should be freed with
mongoc_gridfs_bucket_destroy() or NULL on failure.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_BUCKET_NEW(3)
mongoc_gridfs_bucket_open_download_stream.3
MONGOC_GRIDFS_BUCKET_OPEN_DOWNLOADMSTREAM(3)DFS_BUCKET_OPEN_DOWNLOAD_STREAM(3)
SYNOPSIS
mongoc_stream_t *
mongoc_gridfs_bucket_open_download_stream (mongoc_gridfs_bucket_t *bucket,
const bson_value_t *file_id,
bson_error_t *error);
PARAMETERS
+ bucket: A mongoc_gridfs_bucket_t.
+ file_id: A bson_value_t of the id of the file to download.
+ error: A bson_error_t to receive any error or NULL.
DESCRIPTION
Opens a stream for reading a file from GridFS.
RETURNS
A mongoc_stream_t that can be read from or NULL on failure. Errors on
this stream can be retrieved with mongoc_gridfs_bucket_stream_error().
SEE ALSO:
mongoc_gridfs_bucket_stream_error()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025FS_BUCKET_OPEN_DOWNLOAD_STREAM(3)
mongoc_gridfs_bucket_open_upload_stream.3
MONGOC_GRIDFS_BUCKET_OPEN_UPLOAD_STREAM(3)ocRIDFS_BUCKET_OPEN_UPLOAD_STREAM(3)
SYNOPSIS
mongoc_stream_t *
mongoc_gridfs_bucket_open_upload_stream (mongoc_gridfs_bucket_t *bucket,
const char *filename,
const bson_t *opts,
bson_value_t *file_id,
bson_error_t *error);
PARAMETERS
+ bucket: A mongoc_gridfs_bucket_t.
+ filename: The name of the file to create.
+ opts: A bson_t or NULL.
+ file_id: A bson_value_t to receive the generated id of the file or
NULL.
+ error: A bson_error_t to receive any error or NULL.
opts may be NULL or a BSON document with additional command options:
+ chunkSizeBytes: An int32 chunk size to use for this file. Overrides
the chunkSizeBytes set on bucket.
+ metadata: A bson_t representing metadata to include with the file.
DESCRIPTION
Opens a stream for writing to a new file in GridFS. The file id is gen-
erated automatically. To specify an explicit file id, use
mongoc_gridfs_bucket_open_upload_stream_with_id().
RETURNS
A mongoc_stream_t that can be written to or NULL on failure. Errors on
this stream can be retrieved with mongoc_gridfs_bucket_stream_error().
After calling mongoc_stream_close() the file is completely written in
GridFS.
SEE ALSO:
mongoc_gridfs_bucket_open_upload_stream_with_id()
mongoc_gridfs_bucket_stream_error()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025IDFS_BUCKET_OPEN_UPLOAD_STREAM(3)
mongoc_gridfs_bucket_open_upload_stream_with_id.3
MONGOC_GRIDFS_BUCKET_OPEN_UPLOADOSTREAMoWITHCID(3)PEN_UPLOAD_STREAM_WITH_ID(3)
SYNOPSIS
mongoc_stream_t *
mongoc_gridfs_bucket_open_upload_stream_with_id (mongoc_gridfs_bucket_t *bucket,
const bson_value_t *file_id,
const char *filename,
const bson_t *opts,
bson_error_t *error);
PARAMETERS
+ bucket: A mongoc_gridfs_bucket_t.
+ file_id: A bson_value_t specifying the id of the created file.
+ filename: The name of the file to create.
+ opts: A bson_t or NULL.
+ error: A bson_error_t to receive any error or NULL.
opts may be NULL or a BSON document with additional command options:
+ chunkSizeBytes: An int32 chunk size to use for this file. Overrides
the chunkSizeBytes set on bucket.
+ metadata: A bson_t representing metadata to include with the file.
DESCRIPTION
Opens a stream for writing to a new file in GridFS for a specified file
id. To have libmongoc generate an id, use
mongoc_gridfs_bucket_open_upload_stream().
RETURNS
A mongoc_stream_t that can be written to or NULL on failure. Errors on
this stream can be retrieved with mongoc_gridfs_bucket_stream_error().
After calling mongoc_stream_close() the file is completely written in
GridFS.
SEE ALSO:
mongoc_gridfs_bucket_open_upload_stream()
mongoc_gridfs_bucket_stream_error()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayR12,S2025KET_OPEN_UPLOAD_STREAM_WITH_ID(3)
mongoc_gridfs_bucket_stream_error.3
MONGOC_GRIDFS_BUCKET_STREAM_ERROR(3)ibmongocNGOC_GRIDFS_BUCKET_STREAM_ERROR(3)
SYNOPSIS
bool
mongoc_gridfs_bucket_stream_error (mongoc_stream_t *stream,
bson_error_t *error);
PARAMETERS
+ stream: A mongoc_stream_t created by
mongoc_gridfs_bucket_open_upload_stream(),
mongoc_gridfs_bucket_open_upload_stream_with_id(), or
mongoc_gridfs_bucket_open_download_stream().
+ error: A bson_error_t to receive the possible error.
DESCRIPTION
Retrieves an error for a GridFS stream if one exists.
RETURNS
True if an error occurred on the stream and sets error. False other-
wise.
SEE ALSO:
mongoc_gridfs_bucket_open_upload_stream()
mongoc_gridfs_bucket_open_upload_stream_with_id()
mongoc_gridfs_bucket_open_download_stream()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_GRIDFS_BUCKET_STREAM_ERROR(3)
mongoc_gridfs_bucket_t.3
MONGOC_GRIDFS_BUCKET_T(3) libmongoc MONGOC_GRIDFS_BUCKET_T(3)
SYNOPSIS
#include <mongoc/mongoc.h>
typedef struct _mongoc_gridfs_bucket_t mongoc_gridfs_bucket_t;
DESCRIPTION
mongoc_gridfs_bucket_t provides a spec-compliant MongoDB GridFS imple-
mentation, superseding mongoc_gridfs_t. See the GridFS MongoDB documen-
tation.
THREAD SAFETY
mongoc_gridfs_bucket_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_bucket_t before freeing all de-
rived instances of mongoc_stream_t. The owning mongoc_client_t must
outlive the mongoc_gridfs_bucket_t.
EXAMPLE
example-gridfs-bucket.c
#include <stdio.h>
#include <stdlib.h>
#include <mongoc/mongoc.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;
}
/* 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;
}
SEE ALSO:
The MongoDB GridFS specification.
The non spec-compliant mongoc_gridfs_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_BUCKET_T(3)
mongoc_gridfs_bucket_upload_from_stream.3
MONGOC_GRIDFS_BUCKET_UPLOAD_FROM_STREAM(3)ocRIDFS_BUCKET_UPLOAD_FROM_STREAM(3)
SYNOPSIS
bool
mongoc_gridfs_bucket_upload_from_stream (mongoc_gridfs_bucket_t *bucket,
const char *filename,
mongoc_stream_t *source,
const bson_t *opts,
bson_value_t *file_id,
bson_error_t *error);
PARAMETERS
+ bucket: A mongoc_gridfs_bucket_t.
+ filename: The name of the file to create.
+ source: A mongoc_stream_t used as the source of the data to upload.
+ opts: A bson_t or NULL.
+ file_id: A bson_value_t to receive the generated id of the file or
NULL.
+ error: A bson_error_t to receive any error or NULL.
opts may be NULL or a BSON document with additional command options:
+ chunkSizeBytes: An int32 chunk size to use for this file. Overrides
the chunkSizeBytes set on bucket.
+ metadata: A bson_t representing metadata to include with the file.
DESCRIPTION
Reads from the source stream and writes to a new file in GridFS. The
file id is generated automatically. To specify an explicit file id,
use mongoc_gridfs_bucket_upload_from_stream_with_id().
Reads from the source stream using mongoc_stream_read() until the re-
turn value indicates end-of-file. The source stream is not closed af-
ter calling mongoc_gridfs_bucket_upload_from_stream(); call
mongoc_stream_close() after.
RETURNS
True if the operation succeeded. False otherwise and sets error.
SEE ALSO:
mongoc_stream_file_new() and mongoc_stream_file_new_for_path(), which can be used to create a source stream from a file.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025IDFS_BUCKET_UPLOAD_FROM_STREAM(3)
mongoc_gridfs_bucket_upload_from_stream_with_id.3
MONGOC_GRIDFS_BUCKET_UPLOAD_FROMOSTREAMoWITHCID(3)PLOAD_FROM_STREAM_WITH_ID(3)
SYNOPSIS
bool
mongoc_gridfs_bucket_upload_from_stream_with_id (mongoc_gridfs_bucket_t *bucket,
const bson_value_t *file_id,
const char *filename,
mongoc_stream_t *source,
const bson_t *opts,
bson_error_t *error);
PARAMETERS
+ bucket: A mongoc_gridfs_bucket_t.
+ file_id: A bson_value_t specifying the id of the created file.
+ filename: The name of the file to create.
+ source: A mongoc_stream_t used as the source of the data to upload.
+ opts: A bson_t or NULL.
+ error: A bson_error_t to receive any error or NULL.
opts may be NULL or a BSON document with additional command options:
+ chunkSizeBytes: An int32 chunk size to use for this file. Overrides
the chunkSizeBytes set on bucket.
+ metadata: A bson_t representing metadata to include with the file.
DESCRIPTION
Reads from the source stream and writes to a new file in GridFS. To
have libmongoc generate an id, use
mongoc_gridfs_bucket_upload_from_stream().
Reads from the source stream using mongoc_stream_read() until the re-
turn value indicates end-of-file. The source stream is not closed af-
ter calling mongoc_gridfs_bucket_upload_from_stream(); call
mongoc_stream_close() after.
RETURNS
True if the operation succeeded. False otherwise and sets error.
SEE ALSO:
mongoc_stream_file_new() and mongoc_stream_file_new_for_path(), which can be used to create a source stream from a file.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayR12,S2025KET_UPLOAD_FROM_STREAM_WITH_ID(3)
mongoc_gridfs_create_file.3
MONGOC_GRIDFS_CREATE_FILE(3) libmongoc MONGOC_GRIDFS_CREATE_FILE(3)
SYNOPSIS
mongoc_gridfs_file_t *
mongoc_gridfs_create_file (mongoc_gridfs_t *gridfs,
mongoc_gridfs_file_opt_t *opt);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
+ opt: A mongoc_gridfs_file_opt_t to specify file options.
DESCRIPTION
This function shall create a new mongoc_gridfs_file_t.
Use mongoc_gridfs_file_writev() to write to the file.
RETURNS
Returns a newly allocated mongoc_gridfs_file_t that should be freed
with mongoc_gridfs_file_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_CREATE_FILE(3)
mongoc_gridfs_create_file_from_stream.3
MONGOC_GRIDFS_CREATE_FILE_FROM_STREAM(3)ngoc_GRIDFS_CREATE_FILE_FROM_STREAM(3)
SYNOPSIS
mongoc_gridfs_file_t *
mongoc_gridfs_create_file_from_stream (mongoc_gridfs_t *gridfs,
mongoc_stream_t *stream,
mongoc_gridfs_file_opt_t *opt);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
+ stream: A mongoc_stream_t.
+ opt: A mongoc_gridfs_file_opt_t to specify file options.
DESCRIPTION
This function shall create a new mongoc_gridfs_file_t and fill it with
the contents of stream. Note that this function will read from stream
until End of File, making it best suited for file-backed streams.
RETURNS
A newly allocated mongoc_gridfs_file_t that should be freed with
mongoc_gridfs_file_destroy() when no longer in use. Returns NULL and
logs an error message if there is a network or server error writing
data to the MongoDB server.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025GRIDFS_CREATE_FILE_FROM_STREAM(3)
mongoc_gridfs_destroy.3
MONGOC_GRIDFS_DESTROY(3) libmongoc MONGOC_GRIDFS_DESTROY(3)
SYNOPSIS
void
mongoc_gridfs_destroy (mongoc_gridfs_t *gridfs);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
DESCRIPTION
This function shall destroy the gridfs structure referenced by gridfs
and any resources associated with the gridfs. Does nothing if gridfs is
NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_DESTROY(3)
mongoc_gridfs_drop.3
MONGOC_GRIDFS_DROP(3) libmongoc MONGOC_GRIDFS_DROP(3)
SYNOPSIS
bool
mongoc_gridfs_drop (mongoc_gridfs_t *gridfs, bson_error_t *error);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
Requests that an entire GridFS be dropped, including all files associ-
ated with it.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_DROP(3)
mongoc_gridfs_file_destroy.3
MONGOC_GRIDFS_FILE_DESTROY(3) libmongoc MONGOC_GRIDFS_FILE_DESTROY(3)
SYNOPSIS
void
mongoc_gridfs_file_destroy (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Destroys the mongoc_gridfs_file_t instance and any resources associated
with it. Does nothing if file is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_DESTROY(3)
mongoc_gridfs_file_error.3
MONGOC_GRIDFS_FILE_ERROR(3) libmongoc MONGOC_GRIDFS_FILE_ERROR(3)
SYNOPSIS
bool
mongoc_gridfs_file_error (mongoc_gridfs_file_t *file, bson_error_t *error);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
This function checks to see if there has been an error associated with
the last operation upon file.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns false if there has been no registered error, otherwise true and
error is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_ERROR(3)
mongoc_gridfs_file_get_aliases.3
MONGOC_GRIDFS_FILE_GET_ALIASES(3) libmongoc MONGOC_GRIDFS_FILE_GET_ALIASES(3)
SYNOPSIS
const bson_t *
mongoc_gridfs_file_get_aliases (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Fetches the aliases associated with a gridfs file.
RETURNS
Returns a bson_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_GRIDFS_FILE_GET_ALIASES(3)
mongoc_gridfs_file_get_chunk_size.3
MONGOC_GRIDFS_FILE_GET_CHUNK_SIZE(3)ibmongocNGOC_GRIDFS_FILE_GET_CHUNK_SIZE(3)
SYNOPSIS
int32_t
mongoc_gridfs_file_get_chunk_size (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Fetches the chunk size used with the underlying gridfs file.
RETURNS
A signed 32-bit integer.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_GRIDFS_FILE_GET_CHUNK_SIZE(3)
mongoc_gridfs_file_get_content_type.3
MONGOC_GRIDFS_FILE_GET_CONTENT_TYPE(3)mongocOC_GRIDFS_FILE_GET_CONTENT_TYPE(3)
SYNOPSIS
const char *
mongoc_gridfs_file_get_content_type (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Fetches the content type specified for the underlying file.
RETURNS
Returns a string which should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_GRIDFS_FILE_GET_CONTENT_TYPE(3)
mongoc_gridfs_file_get_filename.3
MONGOC_GRIDFS_FILE_GET_FILENAME(3) libmongocMONGOC_GRIDFS_FILE_GET_FILENAME(3)
SYNOPSIS
const char *
mongoc_gridfs_file_get_filename (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Fetches the filename for the given gridfs file.
RETURNS
A string which should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_GRIDFS_FILE_GET_FILENAME(3)
mongoc_gridfs_file_get_id.3
MONGOC_GRIDFS_FILE_GET_ID(3) libmongoc MONGOC_GRIDFS_FILE_GET_ID(3)
SYNOPSIS
const bson_value_t *
mongoc_gridfs_file_get_id (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Fetches the id of a gridfs file.
The C Driver always uses an ObjectId for _id, but files created by
other drivers may have any type of _id.
RETURNS
Returns a bson_value_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_GET_ID(3)
mongoc_gridfs_file_get_length.3
MONGOC_GRIDFS_FILE_GET_LENGTH(3) libmongoc MONGOC_GRIDFS_FILE_GET_LENGTH(3)
SYNOPSIS
int64_t
mongoc_gridfs_file_get_length (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Fetches the length of the gridfs file in bytes.
RETURNS
A 64-bit signed integer.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_GET_LENGTH(3)
mongoc_gridfs_file_get_md5.3
MONGOC_GRIDFS_FILE_GET_MD5(3) libmongoc MONGOC_GRIDFS_FILE_GET_MD5(3)
SYNOPSIS
const char *
mongoc_gridfs_file_get_md5 (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Fetches the pre-computed MD5 for the underlying gridfs file.
RETURNS
Returns a string that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_GET_MD5(3)
mongoc_gridfs_file_get_metadata.3
MONGOC_GRIDFS_FILE_GET_METADATA(3) libmongocMONGOC_GRIDFS_FILE_GET_METADATA(3)
SYNOPSIS
const bson_t *
mongoc_gridfs_file_get_metadata (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Fetches a bson document containing the metadata for the gridfs file.
RETURNS
Returns a bson_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_GRIDFS_FILE_GET_METADATA(3)
mongoc_gridfs_file_get_upload_date.3
MONGOC_GRIDFS_FILE_GET_UPLOAD_DATE(3)bmongocGOC_GRIDFS_FILE_GET_UPLOAD_DATE(3)
SYNOPSIS
int64_t
mongoc_gridfs_file_get_upload_date (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Fetches the specified upload date of the gridfs file in milliseconds
since the UNIX epoch.
RETURNS
A signed int64 with the upload date in milliseconds since the UNIX
epoch.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_GRIDFS_FILE_GET_UPLOAD_DATE(3)
mongoc_gridfs_file_list_destroy.3
MONGOC_GRIDFS_FILE_LIST_DESTROY(3) libmongocMONGOC_GRIDFS_FILE_LIST_DESTROY(3)
SYNOPSIS
void
mongoc_gridfs_file_list_destroy (mongoc_gridfs_file_list_t *list);
PARAMETERS
+ list: A mongoc_gridfs_file_list_t.
DESCRIPTION
Frees a mongoc_gridfs_file_list_t and releases any associated re-
sources. Does nothing if list is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_GRIDFS_FILE_LIST_DESTROY(3)
mongoc_gridfs_file_list_error.3
MONGOC_GRIDFS_FILE_LIST_ERROR(3) libmongoc MONGOC_GRIDFS_FILE_LIST_ERROR(3)
SYNOPSIS
bool
mongoc_gridfs_file_list_error (mongoc_gridfs_file_list_t *list,
bson_error_t *error);
PARAMETERS
+ list: A mongoc_gridfs_file_list_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
Fetches any error that has occurred while trying to retrieve the file
list.
ERRORS
Errors are propagated via the error parameter.
RETURNS
false if no error has been registered, otherwise true and error is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_LIST_ERROR(3)
mongoc_gridfs_file_list_next.3
MONGOC_GRIDFS_FILE_LIST_NEXT(3) libmongoc MONGOC_GRIDFS_FILE_LIST_NEXT(3)
SYNOPSIS
mongoc_gridfs_file_t *
mongoc_gridfs_file_list_next (mongoc_gridfs_file_list_t *list);
PARAMETERS
+ list: A mongoc_gridfs_file_list_t.
DESCRIPTION
This function shall iterate the underlying gridfs file list, returning
the next file each iteration. This is a blocking function.
RETURNS
A newly allocated mongoc_gridfs_file_t that should be freed with
mongoc_gridfs_file_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_LIST_NEXT(3)
mongoc_gridfs_file_list_t.3
MONGOC_GRIDFS_FILE_LIST_T(3) libmongoc MONGOC_GRIDFS_FILE_LIST_T(3)
SYNOPSIS
#include <mongoc/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_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);
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_LIST_T(3)
mongoc_gridfs_file_opt_t.3
MONGOC_GRIDFS_FILE_OPT_T(3) libmongoc MONGOC_GRIDFS_FILE_OPT_T(3)
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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_OPT_T(3)
mongoc_gridfs_file_readv.3
MONGOC_GRIDFS_FILE_READV(3) libmongoc MONGOC_GRIDFS_FILE_READV(3)
SYNOPSIS
ssize_t
mongoc_gridfs_file_readv (mongoc_gridfs_file_t *file,
mongoc_iovec_t *iov,
size_t iovcnt,
size_t min_bytes,
uint32_t timeout_msec);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ iov: An array of mongoc_iovec_t.
+ iovcnt: The number of elements in iov.
+ min_bytes: The minimum number of bytes that must be read or an error
will be synthesized.
+ timeout_msec: Unused.
DESCRIPTION
This function performs a scattered read from file, potentially blocking
to read from the MongoDB server.
The timeout_msec parameter is unused.
RETURNS
Returns the number of bytes read, or -1 on failure. Use
mongoc_gridfs_file_error() to retrieve error details.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_READV(3)
mongoc_gridfs_file_remove.3
MONGOC_GRIDFS_FILE_REMOVE(3) libmongoc MONGOC_GRIDFS_FILE_REMOVE(3)
SYNOPSIS
bool
mongoc_gridfs_file_remove (mongoc_gridfs_file_t *file, bson_error_t *error);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
Removes file and its data chunks from the MongoDB server.
RETURNS
Returns true if successful. Returns false and sets error if there are
invalid arguments or a server or network error.
ERRORS
Errors are propagated via the error parameter.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_REMOVE(3)
mongoc_gridfs_file_save.3
MONGOC_GRIDFS_FILE_SAVE(3) libmongoc MONGOC_GRIDFS_FILE_SAVE(3)
SYNOPSIS
bool
mongoc_gridfs_file_save (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
Saves modifications to file to the MongoDB server.
If an error occurred, false is returned and the error can be retrieved
with mongoc_gridfs_file_error().
Modifying GridFS files is NOT thread-safe. Only one thread or process
can access a GridFS file while it is being modified.
RETURNS
Returns true if successful, otherwise false.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_SAVE(3)
mongoc_gridfs_file_seek.3
MONGOC_GRIDFS_FILE_SEEK(3) libmongoc MONGOC_GRIDFS_FILE_SEEK(3)
SYNOPSIS
int
mongoc_gridfs_file_seek (mongoc_gridfs_file_t *file, int64_t delta, int whence);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ delta: The amount to move the file position. May be positive or nega-
tive.
+ whence: One of SEEK_SET, SEEK_CUR or SEEK_END.
DESCRIPTION
Adjust the file position pointer in the given file by delta, starting
from the position whence. The whence argument is interpreted as in
fseek(2):
+---------+----------------------------+
|SEEK_SET | Set the position relative |
| | to the start of the file. |
+---------+----------------------------+
|SEEK_CUR | Move delta relative to the |
| | current file position. |
+---------+----------------------------+
|SEEK_END | Move delta relative to the |
| | end of the file. |
+---------+----------------------------+
On success, the file's underlying position pointer is set appropri-
ately. On failure, the file position is NOT changed and errno is set to
indicate the error.
ERRORS
+-------+----------------------------+
|EINVAL | whence is not one of |
| | SEEK_SET, SEEK_CUR or |
| | SEEK_END. |
+-------+----------------------------+
|EINVAL | The resulting file posi- |
| | tion would be negative. |
+-------+----------------------------+
RETURNS
Returns 0 if successful; otherwise -1 and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_SEEK(3)
mongoc_gridfs_file_set_aliases.3
MONGOC_GRIDFS_FILE_SET_ALIASES(3) libmongoc MONGOC_GRIDFS_FILE_SET_ALIASES(3)
SYNOPSIS
void
mongoc_gridfs_file_set_aliases (mongoc_gridfs_file_t *file, const bson_t *bson);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ bson: A bson_t containing the aliases.
DESCRIPTION
Sets the aliases for a gridfs file.
You need to call mongoc_gridfs_file_save() to persist this change.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_GRIDFS_FILE_SET_ALIASES(3)
mongoc_gridfs_file_set_content_type.3
MONGOC_GRIDFS_FILE_SET_CONTENT_TYPE(3)mongocOC_GRIDFS_FILE_SET_CONTENT_TYPE(3)
SYNOPSIS
void
mongoc_gridfs_file_set_content_type (mongoc_gridfs_file_t *file,
const char *content_type);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ str: A string containing the content type.
DESCRIPTION
Sets the content type for the gridfs file. This should be something
like "text/plain".
You need to call mongoc_gridfs_file_save() to persist this change.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_GRIDFS_FILE_SET_CONTENT_TYPE(3)
mongoc_gridfs_file_set_filename.3
MONGOC_GRIDFS_FILE_SET_FILENAME(3) libmongocMONGOC_GRIDFS_FILE_SET_FILENAME(3)
SYNOPSIS
void
mongoc_gridfs_file_set_filename (mongoc_gridfs_file_t *file,
const char *filename);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ str: A UTF-8 encoded string containing the filename.
DESCRIPTION
Sets the filename for file.
You need to call mongoc_gridfs_file_save() to persist this change.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_GRIDFS_FILE_SET_FILENAME(3)
mongoc_gridfs_file_set_id.3
MONGOC_GRIDFS_FILE_SET_ID(3) libmongoc MONGOC_GRIDFS_FILE_SET_ID(3)
SYNOPSIS
bool
mongoc_gridfs_file_set_id (mongoc_gridfs_file_t *file,
const bson_value_t *id,
bson_error_t error);
PARAMETERS
+ file: A :symbol:` mongoc_gridfs_file_t <mongoc_gridfs_file_t>`.
+ id: A bson_value_t.
+ error: A bson_error_t.
DESCRIPTION
Sets the id of file to any BSON type.
If an error occurred, false is returned.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and logs an error.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_SET_ID(3)
mongoc_gridfs_file_set_md5.3
MONGOC_GRIDFS_FILE_SET_MD5(3) libmongoc MONGOC_GRIDFS_FILE_SET_MD5(3)
SYNOPSIS
void
mongoc_gridfs_file_set_md5 (mongoc_gridfs_file_t *file, const char *md5);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ str: A string containing the MD5 of the file.
DESCRIPTION
Sets the MD5 checksum for file.
You need to call mongoc_gridfs_file_save() to persist this change.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_SET_MD5(3)
mongoc_gridfs_file_set_metadata.3
MONGOC_GRIDFS_FILE_SET_METADATA(3) libmongocMONGOC_GRIDFS_FILE_SET_METADATA(3)
SYNOPSIS
void
mongoc_gridfs_file_set_metadata (mongoc_gridfs_file_t *file,
const bson_t *metadata);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ bson: A bson_t containing metadata for file.
DESCRIPTION
Sets the metadata associated with file.
You need to call mongoc_gridfs_file_save() to persist this change.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_GRIDFS_FILE_SET_METADATA(3)
mongoc_gridfs_file_t.3
MONGOC_GRIDFS_FILE_T(3) libmongoc MONGOC_GRIDFS_FILE_T(3)
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, meta-
data, 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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_T(3)
mongoc_gridfs_file_tell.3
MONGOC_GRIDFS_FILE_TELL(3) libmongoc MONGOC_GRIDFS_FILE_TELL(3)
SYNOPSIS
uint64_t
mongoc_gridfs_file_tell (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
DESCRIPTION
This function returns the current position indicator within file.
RETURNS
Returns a file position as an unsigned 64-bit integer.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_TELL(3)
mongoc_gridfs_file_writev.3
MONGOC_GRIDFS_FILE_WRITEV(3) libmongoc MONGOC_GRIDFS_FILE_WRITEV(3)
SYNOPSIS
ssize_t
mongoc_gridfs_file_writev (mongoc_gridfs_file_t *file,
const mongoc_iovec_t *iov,
size_t iovcnt,
uint32_t timeout_msec);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
+ iov: An array of mongoc_iovec_t.
+ iovcnt: The number of elements in iov.
+ timeout_msec: Unused.
DESCRIPTION
Performs a gathered write to the underlying gridfs file.
The timeout_msec parameter is unused.
Modifying GridFS files is NOT thread-safe. Only one thread or process
can access a GridFS file while it is being modified.
RETURNS
Returns the number of bytes written, or -1 on failure. Use
mongoc_gridfs_file_error() to retrieve error details.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FILE_WRITEV(3)
mongoc_gridfs_find_one_by_filename.3
MONGOC_GRIDFS_FIND_ONE_BY_FILENAME(3)bmongocGOC_GRIDFS_FIND_ONE_BY_FILENAME(3)
SYNOPSIS
mongoc_gridfs_file_t *
mongoc_gridfs_find_one_by_filename (mongoc_gridfs_t *gridfs,
const char *filename,
bson_error_t *error);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
+ filename: A UTF-8 encoded string containing the filename.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
Finds the first file matching the filename specified. If there is an
error, NULL is returned and error is filled out; if there is no error
but no matching file is found, NULL is returned and the error code and
domain are 0.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns a newly allocated mongoc_gridfs_file_t if successful. You must
free the resulting file with mongoc_gridfs_file_destroy() when no
longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_GRIDFS_FIND_ONE_BY_FILENAME(3)
mongoc_gridfs_find_one_with_opts.3
MONGOC_GRIDFS_FIND_ONE_WITH_OPTS(3)libmongocONGOC_GRIDFS_FIND_ONE_WITH_OPTS(3)
SYNOPSIS
mongoc_gridfs_file_t *
mongoc_gridfs_find_one_with_opts (mongoc_gridfs_t *gridfs,
const bson_t *filter,
const bson_t *opts,
bson_error_t *error);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
+ filter: A bson_t containing the query to execute.
+ opts: A bson_t query options, including sort order and which fields
to return. Can be NULL.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
Find the first GridFS file matching filter. If there is an error, NULL
is returned and error is filled out; if there is no error but no match-
ing file is found, NULL is returned and the error code and domain are
0.
See mongoc_collection_find_with_opts() for a description of the filter
and opts parameters.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
ERRORS
Errors are propagated via the error parameter.
RETURNS
Returns a newly allocated mongoc_gridfs_file_t if successful. You must
free the resulting file with mongoc_gridfs_file_destroy() when no
longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_GRIDFS_FIND_ONE_WITH_OPTS(3)
mongoc_gridfs_find_with_opts.3
MONGOC_GRIDFS_FIND_WITH_OPTS(3) libmongoc MONGOC_GRIDFS_FIND_WITH_OPTS(3)
SYNOPSIS
mongoc_gridfs_file_list_t *
mongoc_gridfs_find_with_opts (mongoc_gridfs_t *gridfs,
const bson_t *filter,
const bson_t *opts);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
+ filter: A bson_t containing the query to execute.
+ opts: A bson_t query options, including sort order and which fields
to return. Can be NULL.
DESCRIPTION
Finds all gridfs files matching filter. You can iterate the matched
gridfs files with the resulting file list.
See mongoc_collection_find_with_opts() for a description of the filter
and opts parameters.
This function is considered a retryable read operation. Upon a tran-
sient error (a network error, errors due to replica set failover, etc.)
the operation is safely retried once. If retryreads is false in the
URI (see mongoc_uri_t) the retry behavior does not apply.
RETURNS
A newly allocated mongoc_gridfs_file_list_t that should be freed with
mongoc_gridfs_file_list_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_FIND_WITH_OPTS(3)
mongoc_gridfs_get_chunks.3
MONGOC_GRIDFS_GET_CHUNKS(3) libmongoc MONGOC_GRIDFS_GET_CHUNKS(3)
SYNOPSIS
mongoc_collection_t *
mongoc_gridfs_get_chunks (mongoc_gridfs_t *gridfs);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
DESCRIPTION
Returns a mongoc_collection_t that contains the chunks for files. This
instance is owned by the mongoc_gridfs_t instance and should not be
modified or freed.
RETURNS
Returns a mongoc_collection_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_GET_CHUNKS(3)
mongoc_gridfs_get_files.3
MONGOC_GRIDFS_GET_FILES(3) libmongoc MONGOC_GRIDFS_GET_FILES(3)
SYNOPSIS
mongoc_collection_t *
mongoc_gridfs_get_files (mongoc_gridfs_t *gridfs);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
DESCRIPTION
Retrieves the mongoc_collection_t containing the file metadata for
GridFS. This instance is owned by the mongoc_gridfs_t and should not be
modified or freed.
RETURNS
Returns a mongoc_collection_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_GET_FILES(3)
mongoc_gridfs_remove_by_filename.3
MONGOC_GRIDFS_REMOVE_BY_FILENAME(3)libmongocONGOC_GRIDFS_REMOVE_BY_FILENAME(3)
SYNOPSIS
bool
mongoc_gridfs_remove_by_filename (mongoc_gridfs_t *gridfs,
const char *filename,
bson_error_t *error);
PARAMETERS
+ gridfs: A mongoc_gridfs_t.
+ filename: A UTF-8 encoded string containing the filename.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
Removes all files matching filename and their data chunks from the Mon-
goDB server.
RETURNS
Returns true if successful, including when no files match. Returns
false and sets error if there are invalid arguments or a server or net-
work error.
ERRORS
Errors are propagated via the error parameter.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_GRIDFS_REMOVE_BY_FILENAME(3)
mongoc_gridfs_t.3
MONGOC_GRIDFS_T(3) libmongoc MONGOC_GRIDFS_T(3)
WARNING:
This GridFS implementation does not conform to the MongoDB GridFS
specification. For a spec compliant implementation, use
mongoc_gridfs_bucket_t.
SYNOPSIS
#include <mongoc/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 prac-
tical 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 ex-
isting gridfs object, just use them with caution.
mongoc_gridfs also integrates tightly with the mongoc_stream_t abstrac-
tion, 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 in-
stances of mongoc_gridfs_file_t and mongoc_gridfs_file_list_t.
EXAMPLE
example-gridfs.c
#include <assert.h>
#include <mongoc/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;
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: %s\n"
"error message: %s\n",
uri_string,
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) {
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 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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_GRIDFS_T(3)
mongoc_handshake_data_append.3
MONGOC_HANDSHAKE_DATA_APPEND(3) libmongoc MONGOC_HANDSHAKE_DATA_APPEND(3)
SYNOPSIS
bool
mongoc_handshake_data_append (const char *driver_name,
const char *driver_version,
const char *platform);
Appends the given strings to the handshake data for the underlying C
Driver.
DESCRIPTION
This function is intended for use by drivers which wrap the C Driver.
Calling this function will store the given strings as handshake data
about the system and driver by appending them to the handshake data for
the underlying C Driver. These values, along with other handshake data
collected during mongoc_init will be sent to the server as part of the
initial connection handshake in the "client" document. This function
must not be called more than once, or after server monitoring begins.
For a single-threaded mongoc_client_t, server monitoring begins on the
first operation requiring a server. For a mongoc_client_pool_t, server
monitoring begins on the first call to :symbol:`mongoc_client_pool_pop.
The passed in strings are copied, and don't have to remain valid after
the call to mongoc_handshake_data_append(). The driver may store trun-
cated versions of the passed in strings.
NOTE:
This function allocates memory, and therefore caution should be used
when using this in conjunction with bson_mem_set_vtable(). If this
function is called before bson_mem_set_vtable(), then
bson_mem_restore_vtable() must be called before calling
mongoc_cleanup(). Failure to do so will result in memory being freed
by the wrong allocator.
PARAMETERS
+ driver_name: An optional string storing the name of the wrapping
driver
+ driver_version: An optional string storing the version of the wrap-
ping driver.
+ platform: An optional string storing any information about the cur-
rent platform, for example configure options or compile flags.
RETURNS
true if the given fields are set successfully. Otherwise, it returns
false and logs an error.
The default handshake data the driver sends with "hello" looks some-
thing like:
client: {
driver: {
name: "mongoc",
version: "1.5.0"
},
os: {...},
platform: "CC=gcc CFLAGS=-Wall -pedantic"
}
If we call mongoc_handshake_data_append() ("phongo", "1.1.8", "CC=clang
/ ") and it returns true, the driver sends handshake data like:
client: {
driver: {
name: "mongoc / phongo",
version: "1.5.0 / 1.1.8"
},
os: {...},
platform: "CC=clang / gcc CFLAGS=-Wall -pedantic"
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_HANDSHAKE_DATA_APPEND(3)
mongoc_host_list_t.3
MONGOC_HOST_LIST_T(3) libmongoc MONGOC_HOST_LIST_T(3)
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().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_HOST_LIST_T(3)
mongoc_init.3
MONGOC_INIT(3) libmongoc MONGOC_INIT(3)
SYNOPSIS
void
mongoc_init (void);
DESCRIPTION
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.
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 re-
lease 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().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_INIT(3)
mongoc_init_cleanup.3
MONGOC_INIT_CLEANUP(3) libmongoc MONGOC_INIT_CLEANUP(3)
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.
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 re-
lease 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().
Changed in version 2.0.0: Versions prior to 2.0.0 supported a non-por-
table automatic initialization and cleanup with the CMake option EN-
ABLE_AUTOMATIC_INIT_AND_CLEANUP. This was removed in 2.0.0. Ensure your
application call mongoc_init() and mongoc_cleanup().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_INIT_CLEANUP(3)
mongoc_insert_flags_t.3
MONGOC_INSERT_FLAGS_T(3) libmongoc MONGOC_INSERT_FLAGS_T(3)
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 bit-
wise or'd together. They may modify how an insert happens on the Mon-
goDB server.
FLAG VALUES
+--------------------------+----------------------------+
|MONGOC_INSERT_NONE | Specify no insert flags. |
+--------------------------+----------------------------+
|MONGOC_INSERT_CON- | Continue inserting docu- |
|TINUE_ON_ERROR | ments from the insertion |
| | set even if one insert |
| | fails. |
+--------------------------+----------------------------+
|MONGOC_INSERT_NO_VALIDATE | Do not validate insertion |
| | documents before perform- |
| | ing an insert. Validation |
| | can be expensive, so this |
| | can save some time if you |
| | know your documents are |
| | already valid. |
+--------------------------+----------------------------+
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_INSERT_FLAGS_T(3)
mongoc_iovec_t.3
MONGOC_IOVEC_T(3) libmongoc MONGOC_IOVEC_T(3)
SYNOPSIS
SYNOPSIS
#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 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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_IOVEC_T(3)
mongoc_logging.3
MONGOC_LOGGING(3) libmongoc MONGOC_LOGGING(3)
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.
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.
Macros
To make logging a little less painful, various helper macros are pro-
vided. 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 std-
out, or to stderr for warnings, critical messages, and errors. You can
override the handler with mongoc_log_set_handler(). Your handler func-
tion 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_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 be-
fore 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 er-
rors, provide an empty log handler:
mongoc_log_set_handler (NULL, NULL);
Tracing
If compiling your own copy of the MongoDB C driver, consider configur-
ing with -DENABLE_TRACING=ON to enable function tracing and hex dumps
of network packets to STDERR and STDOUT during development and debug-
ging.
This is especially useful when debugging what may be going on inter-
nally in the driver.
Trace messages can be enabled and disabled by calling mon-
goc_log_trace_enable() and mongoc_log_trace_disable()
NOTE:
Compiling the driver with -DENABLE_TRACING=ON will affect its per-
formance. Disabling tracing with mongoc_log_trace_disable() signifi-
cantly reduces the overhead, but cannot remove it completely.
STRUCTURED LOGGING
This document describes a newer "structured" logging facility which re-
ports 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().
Options
Structured log settings are tracked explicitly by a
mongoc_structured_log_opts_t instance.
Like other drivers supporting structured logging, we take default set-
tings from environment variables and offer additional optional program-
matic 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 pro-
grammatic 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 han-
dler, 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 maxi-
mum 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().
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 cap-
tured 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 warn-
ings 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 implementa-
tion-specific value near the maximum representable length. By de-
fault, the limit is 1000 bytes. This limit affects interior docu-
ments 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:
When a file path is given for MONGODB_LOG_PATH, each log instance
(one stand-alone client or pool) will separately open this file
for append. The results are operating system specific. On
UNIX-like platforms each instance's output will be interleaved, in
most cases without splitting individual log messages. Notably on
Windows the file will be opened in exclusive mode by the first in-
stance and subsequent instances will fail, falling back on the de-
fault of stderr. Applications that use multiple processes or mul-
tiple client pools will likely want to supply a log handler that
annotates each message with information about its originating log
instance.
+ MONGODB_LOG_COMMAND: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_COMMAND.
+ MONGODB_LOG_TOPOLOGY: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_TOPOLOGY.
+ MONGODB_LOG_SERVER_SELECTION: A log level name to set as the maximum
for MONGOC_STRUCTURED_LOG_COMPONENT_SERVER_SELECTION.
+ MONGODB_LOG_CONNECTION: A log level name to set as the maximum for
MONGOC_STRUCTURED_LOG_COMPONENT_CONNECTION.
+ MONGODB_LOG_ALL: A log level name applied to all components not oth-
erwise specified.
Note that log level names are always case insensitive. This is a full
list of recognized names, including allowed aliases:
+ 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 allocated with
mongoc_structured_log_opts_new(), or NULL.
Description
This function releases all resources associated with a
mongoc_structured_log_opts_t. Does nothing if opts is NULL.
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 to be called to handle structured log messages, as a
mongoc_structured_log_func_t.
The callback is given a mongoc_structured_log_entry_t as a handle for
obtaining additional information about the log message. This entry
pointer is only valid during a callback, because it's a low cost refer-
ence to temporary data.
Structured log handlers must be thread-safe if they will be used with
mongoc_client_pool_t. Handlers must avoid unbounded recursion, prefer-
ably by avoiding the use of any libmongoc client or pool which uses the
same handler.
This function always replaces the default log handler from
mongoc_structured_log_opts_new(), if it was still set. If the log_func
is set to NULL, structured logging will be disabled.
Parameters
+ opts: Structured log options, allocated with
mongoc_structured_log_opts_new().
+ log_func: The handler to install, a mongoc_structured_log_func_t, or
NULL to disable structured logging.
+ user_data: Optional user data, passed on to the 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 be-
low this severity level will be passed to mongoc_structured_log_func_t.
By default, each component's log level may come from environment vari-
ables. 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 to set 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 supplied parameters were in-
correct.
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 all per-component maximum log levels to the same value. Only log
messages at or below this severity level will be passed to
mongoc_structured_log_func_t. Effective even for logging components
not known at compile-time.
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 in-
correct.
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 requested by environment variables: MON-
GODB_LOG_ALL for all components, followed by per-component log levels
MONGODB_LOG_COMMAND, MONGODB_LOG_CONNECTION, MONGODB_LOG_TOPOLOGY, and
MONGODB_LOG_SERVER_SELECTION.
Expects the value to be recognizable by
mongoc_structured_log_get_named_level(). Parse errors may cause a
warning message, delivered via unstructured logging.
Component levels with no valid environment variable setting will be
left unmodified.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may 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(). This
will process the environment a second time, allowing it to override
customized defaults.
Returns
Returns true on success. If warnings are encountered in the environ-
ment, returns false and may log additional information to the unstruc-
tured logging facility. Note that, by design, these errors are by de-
fault 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_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 a specific component, as a
mongoc_structured_log_level_t. This may 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
may be the default obtained from environment variables. If an invalid
or unknown component enum is given, returns the lowest log level.
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 appear serialized in JSON
form as part of a structured log message.
Serialized JSON will be truncated at this limit, interpreted as a count
of UTF-8 encoded bytes. Truncation will be indicated with a ... suffix,
the length of which is not included in the max document length. If
truncation at the exact indicated length would split a valid UTF-8 se-
quence, we instead truncate the document earlier at the nearest bound-
ary between code points.
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 trunca-
tion. Values near or above INT_MAX will be rejected.
Returns
Returns true on success, or false if the supplied maximum length 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 a description of the supported en-
vironment variable formats.
Parse errors may cause a warning message, delivered via unstructured
logging.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may call
mongoc_structured_log_opts_set_max_document_length_from_env() after
calling mongoc_structured_log_opts_set_max_document_length(). This
will process the environment a second time, allowing it to override
customized defaults.
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 de-
sign, these errors are by default non-fatal. When
mongoc_structured_log_opts_new() internally calls this function, it ig-
nores 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 set in opts, as a size_t.
SEE ALSO:
Structured Logging
SEE ALSO:
Structured Logging
Levels and Components
Log levels and components are defined as mongoc_structured_log_level_t
and mongoc_structured_log_component_t enumerations. Utilities are pro-
vided to convert between these values and their standard string repre-
sentations. The string values are case-insensitive.
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 the available log levels for
use with structured logging.
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, returns a pointer to a constant string that
should not be freed. If the level has no known name, 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.
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, returns true and writes the level enum to
*out. If the level name is not known, returns false and does not write
*out.
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. Applications should never rely on having an exhaustive
list of all log components. Instead, use
mongoc_structured_log_opts_set_max_level_for_all_components() to set a
default level if needed.
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.
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, returns true and writes the component
enum to *out. If the component name is not known, returns false and
does not write *out.
SEE ALSO:
Structured Logging
SEE ALSO:
Structured Logging
SEE ALSO:
mongoc_structured_log_get_level_name mongoc_struc-
tured_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 in-
stance of the structured logging subsystem, with its own settings and
handler.
When using mongoc_client_pool_t, the pooled clients all share a common
logging instance. Handlers must be thread-safe.
The handler is called for each log entry with a level no greater than
its component's maximum. A mongoc_structured_log_entry_t pointer pro-
vides access to further details, during the handler only.
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.
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(). Struc-
tured log handlers must be thread-safe if they will be used with
mongoc_client_pool_t. Handlers must avoid unbounded recursion, prefer-
ably by avoiding the use of any libmongoc client or pool which uses the
same handler.
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 within the handler by a short-lived
mongoc_structured_log_entry_t pointer. During the handler, this
pointer can be used to access the individual properties of an entry:
its level, component, and message.
The message will be assembled as a bson_t only when explicitly re-
quested by a call to mongoc_structured_log_entry_message_as_bson().
This results in a standalone document that may be retained for any
amount of time and must be explicitly destroyed.
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 which represents
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 individual aspects
of the log entry.
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 struc-
tured log handler. It should not be freed or modified.
Identical to the value of the message key in the document returned by
mongoc_structured_log_entry_message_as_bson().
This is not a complete string representation of the structured log, but
rather a standardized identifier for a particular log event.
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 rep-
resentation. When possible, a log handler should avoid serializing log
messages that will be discarded. 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
/* 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 proceses 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_en-
try_get_level mongoc_structured_log_entry_message_as_bson
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_LOGGING(3)
mongoc_oidc_callback_destroy.3
MONGOC_OIDC_CALLBACK_DESTROY(3) libmongoc MONGOC_OIDC_CALLBACK_DESTROY(3)
SYNOPSIS
void
mongoc_oidc_callback_destroy (mongoc_oidc_callback_t *callback)
Release all resources associated with the given mongoc_oidc_callback_t
object.
WARNING:
The lifetime of the object pointed to by user_data is managed the
user, not by mongoc_oidc_callback_t!
PARAMETERS
+ callback: a mongoc_oidc_callback_t or NULL.
SEE ALSO:
+ mongoc_oidc_callback_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OIDC_CALLBACK_DESTROY(3)
mongoc_oidc_callback_fn_t.3
MONGOC_OIDC_CALLBACK_FN_T(3) libmongoc MONGOC_OIDC_CALLBACK_FN_T(3)
SYNOPSIS
typedef mongoc_oidc_credential_t *(*mongoc_oidc_callback_fn_t) (mongoc_oidc_callback_params_t *params);
The type of the function pointer stored by mongoc_oidc_callback_t.
PARAMETERS
+ params: A mongoc_oidc_callback_params_t object representing 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.
+ The function MUST return a mongoc_oidc_credential_t object to indi-
cate 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 is ignored if the return value is
not NULL.
SEE ALSO:
+ mongoc_oidc_callback_t
+ mongoc_oidc_callback_params_t
+ mongoc_oidc_credential_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OIDC_CALLBACK_FN_T(3)
mongoc_oidc_callback_get_fn.3
MONGOC_OIDC_CALLBACK_GET_FN(3) libmongoc MONGOC_OIDC_CALLBACK_GET_FN(3)
SYNOPSIS
mongoc_oidc_callback_fn_t
mongoc_oidc_callback_get_fn (const mongoc_oidc_callback_t *callback);
Return the stored pointer to the callback function.
PARAMETERS
+ callback: a mongoc_oidc_callback_t.
RETURNS
A mongoc_oidc_callback_fn_t.
SEE ALSO:
+ mongoc_oidc_callback_t
+ mongoc_oidc_callback_fn_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OIDC_CALLBACK_GET_FN(3)
mongoc_oidc_callback_get_user_data.3
MONGOC_OIDC_CALLBACK_GET_USER_DATA(3)bmongocGOC_OIDC_CALLBACK_GET_USER_DATA(3)
SYNOPSIS
void *
mongoc_oidc_callback_get_user_data (const mongoc_oidc_callback_t *callback);
Return the stored pointer to user data.
PARAMETERS
+ callback: a mongoc_oidc_callback_t.
RETURNS
A pointer to user data or NULL.
SEE ALSO:
+ mongoc_oidc_callback_t
+ mongoc_oidc_callback_set_user_data()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_OIDC_CALLBACK_GET_USER_DATA(3)
mongoc_oidc_callback_new.3
MONGOC_OIDC_CALLBACK_NEW(3) libmongoc MONGOC_OIDC_CALLBACK_NEW(3)
SYNOPSIS
mongoc_oidc_callback_t *
mongoc_oidc_callback_new (mongoc_oidc_callback_fn_t fn)
Create a new mongoc_oidc_callback_t object which stores the provided
OIDC callback function.
Equivalent to calling mongoc_oidc_callback_new_with_user_data() with
user_data set to NULL.
PARAMETERS
+ fn: a mongoc_oidc_callback_fn_t. Must not be NULL.
RETURNS
A new mongoc_oidc_callback_t that must be freed with
mongoc_oidc_callback_destroy(), or NULL when an invalid argument was
given.
SEE ALSO:
+ mongoc_oidc_callback_t
+ mongoc_oidc_callback_new_with_user_data()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OIDC_CALLBACK_NEW(3)
mongoc_oidc_callback_new_with_user_data.3
MONGOC_OIDC_CALLBACK_NEW_WITH_USER_DATA(3)ocIDC_CALLBACK_NEW_WITH_USER_DATA(3)
SYNOPSIS
mongoc_oidc_callback_t *
mongoc_oidc_callback_new_with_user_data (mongoc_oidc_callback_fn_t fn, void *user_data)
Create a new mongoc_oidc_callback_t object which stores the provided
OIDC callback function and pointer to user data.
WARNING:
The lifetime of the object pointed to by user_data is managed the
user, not by mongoc_oidc_callback_t!
PARAMETERS
+ fn: a mongoc_oidc_callback_fn_t. Must not be NULL.
+ user_data: a pointer to user data or NULL.
RETURNS
A new mongoc_oidc_callback_t that must be freed with
mongoc_oidc_callback_destroy(), or NULL when an invalid argument was
given.
SEE ALSO:
+ mongoc_oidc_callback_t
+ mongoc_oidc_callback_new()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025DC_CALLBACK_NEW_WITH_USER_DATA(3)
mongoc_oidc_callback_params_cancel_with_timeout.3
MONGOC_OIDC_CALLBACK_PARAMS_CANCEL_WITHoTIMEOUT(3)ARAMS_CANCEL_WITH_TIMEOUT(3)
SYNOPSIS
mongoc_oidc_credential_t *
mongoc_oidc_callback_params_cancel_with_timeout (mongoc_oidc_callback_params_t *params);
Set the out parameter indicating cancellation of the callback function
due to a timeout instead of an error.
NOTE:
If the callback function returns a not-null value, the value of this
out parameter is ignored.
PARAMETERS
+ params: a mongoc_oidc_callback_params_t.
RETURNS
NULL.
SEE ALSO:
+ mongoc_oidc_callback_params_t
+ mongoc_oidc_callback_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayI12,C2025ACK_PARAMS_CANCEL_WITH_TIMEOUT(3)
mongoc_oidc_callback_params_get_timeout.3
MONGOC_OIDC_CALLBACK_PARAMS_GET_TIMEOUT(3)ocIDC_CALLBACK_PARAMS_GET_TIMEOUT(3)
SYNOPSIS
const int64_t *
mongoc_oidc_callback_params_get_timeout (const mongoc_oidc_callback_params_t *params);
Return a value comparable with System Clock to determine when a timeout
must occur.
A NULL (unset) return value means "infinite" timeout.
PARAMETERS
+ params: a mongoc_oidc_callback_params_t.
RETURNS
A value comparable with System Clock, or NULL.
LIFECYCLE
The pointed-to int64_t is only valid for the duration of the invocation
of the OIDC callback function.
SEE ALSO:
+ mongoc_oidc_callback_params_t
+ mongoc_oidc_callback_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025DC_CALLBACK_PARAMS_GET_TIMEOUT(3)
mongoc_oidc_callback_params_get_user_data.3
MONGOC_OIDC_CALLBACK_PARAMS_GET_USERiDATA(3)C_CALLBACK_PARAMS_GET_USER_DATA(3)
SYNOPSIS
void *
mongoc_oidc_callback_params_get_user_data (const mongoc_oidc_callback_params_t *params);
Return the pointer to user data which was stored by an associated
mongoc_oidc_callback_t object.
PARAMETERS
+ params: a mongoc_oidc_callback_params_t.
RETURNS
A pointer to user data or NULL.
LIFECYCLE
The lifetime of the object pointed to by user_data is managed the user.
SEE ALSO:
+ mongoc_oidc_callback_params_t
+ mongoc_oidc_callback_t
+ mongoc_oidc_callback_set_user_data()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025_CALLBACK_PARAMS_GET_USER_DATA(3)
mongoc_oidc_callback_params_get_username.3
MONGOC_OIDC_CALLBACK_PARAMS_GET_USERNAME(3)cDC_CALLBACK_PARAMS_GET_USERNAME(3)
SYNOPSIS
const char *
mongoc_oidc_callback_params_get_username (const mongoc_oidc_callback_params_t *params);
Return the username component of the URI of an associated
mongoc_client_t or mongoc_client_pool_t object.
PARAMETERS
+ params: a mongoc_oidc_callback_params_t.
RETURNS
A string which must not be modified or freed, or NULL.
LIFECYCLE
The string is only valid for the duration of the invocation of the OIDC
callback function.
SEE ALSO:
+ mongoc_oidc_callback_params_t
+ mongoc_oidc_callback_t
+ mongoc_uri_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025C_CALLBACK_PARAMS_GET_USERNAME(3)
mongoc_oidc_callback_params_get_version.3
MONGOC_OIDC_CALLBACK_PARAMS_GET_VERSION(3)ocIDC_CALLBACK_PARAMS_GET_VERSION(3)
SYNOPSIS
int32_t
mongoc_oidc_callback_params_get_version (const mongoc_oidc_callback_params_t *params);
Return the OIDC callback API version number.
PARAMETERS
+ params: a mongoc_oidc_callback_params_t.
RETURNS
A positive integer.
SEE ALSO:
+ mongoc_oidc_callback_params_t
+ mongoc_oidc_callback_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025DC_CALLBACK_PARAMS_GET_VERSION(3)
mongoc_oidc_callback_params_t.3
MONGOC_OIDC_CALLBACK_PARAMS_T(3) libmongoc MONGOC_OIDC_CALLBACK_PARAMS_T(3)
SYNOPSIS
typedef struct _mongoc_oidc_callback_params_t mongoc_oidc_callback_params_t;
Represents the in/out parameters of a mongoc_oidc_callback_t.
The parameters will be passed to the mongoc_oidc_callback_fn_t stored
in an mongoc_oidc_callback_t object when it is invoked by an
mongoc_client_t or mongoc_client_pool_t object.
PARAMETERS
The list of currently supported parameters are:
+--------------------+----------+---------------------+
|Parameter | Versions | Description |
+--------------------+----------+---------------------+
|version | 1 | The current OIDC |
| | | callback API ver- |
| | | sion number. |
+--------------------+----------+---------------------+
|user_data | 1 | A pointer to data |
| | | provided by the |
| | | user. |
+--------------------+----------+---------------------+
|timeout | 1 | The timestamp after |
| | | which the callback |
| | | function must re- |
| | | port a timeout. |
+--------------------+----------+---------------------+
|username | 1 | The username speci- |
| | | fied by the URI of |
| | | the associated |
| | | client object. |
+--------------------+----------+---------------------+
|cancel_with_timeout | 1 | An out parameter |
| | | indicating cancel- |
| | | lation of the call- |
| | | back function due |
| | | to a timeout in- |
| | | stead of an error. |
+--------------------+----------+---------------------+
The "Version" column indicates the OIDC callback API versions for which
the parameter is applicable.
Version
The version parameter is used to communicate backward compatible
changes to the OIDC callback API (i.e. the addition of a new parame-
ter).
This parameter may be used to detect when existing usage of
mongoc_oidc_callback_t or a relevant callback function may need to be
reviewed.
For example, users may add the following check to their callback func-
tion:
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 may be used to pass additional arguments to the
callback function or to return additional values out of the callback
function.
This parameter must be set in advance via
mongoc_oidc_callback_set_user_data() before the mongoc_oidc_callback_t
object is associated with a mongoc_client_t or mongoc_client_pool_t ob-
ject.
WARNING:
The lifetime of the object pointed to by user_data is managed the
user, not by mongoc_oidc_callback_t!
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);
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 used to determine when the callback function
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
from which the callback function is invoked.
Cancel With Timeout
The cancel_with_timeout out parameter indicates cancellation of the
callback function due to a timeout instead of an error.
IMPORTANT:
The callback function MUST return NULL, otherwise the invocation
will be interpreted as a success even when cancel_with_timeout is
set.
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
A NULL return value (without setting cancel_with_timeout) indicates
failure to provide an access token due to an error.
IMPORTANT:
The callback function MUST return NULL, otherwise the invocation
will be interpreted as a success.
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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OIDC_CALLBACK_PARAMS_T(3)
mongoc_oidc_callback_set_user_data.3
MONGOC_OIDC_CALLBACK_SET_USER_DATA(3)bmongocGOC_OIDC_CALLBACK_SET_USER_DATA(3)
SYNOPSIS
void
mongoc_oidc_callback_set_user_data (mongoc_oidc_callback_t *callback, void *user_data);
Store the provided pointer to user data.
WARNING:
The lifetime of the object pointed to by user_data is managed the
user, not by mongoc_oidc_callback_t!
PARAMETERS
+ callback: a mongoc_oidc_callback_t.
+ user_data: a pointer to user data or NULL.
SEE ALSO:
+ mongoc_oidc_callback_t
+ mongoc_oidc_callback_get_user_data()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_OIDC_CALLBACK_SET_USER_DATA(3)
mongoc_oidc_callback_t.3
MONGOC_OIDC_CALLBACK_T(3) libmongoc MONGOC_OIDC_CALLBACK_T(3)
SYNOPSIS
typedef struct _mongoc_oidc_callback_t mongoc_oidc_callback_t;
mongoc_oidc_callback_t represents a user-defined callback function
mongoc_oidc_callback_fn_t that returns an OIDC access token.
The callback may be used to integrate with OIDC providers that are not
supported by the built-in provider integrations (Authentication Mecha-
nism Properties).
LIFECYCLE
The function and optional user data stored by mongoc_oidc_callback_t
must outlive any associated client or client pool object which may in-
voke the stored callback function.
THREAD SAFETY
The callback function stored by a mongoc_oidc_callback_t object will be
invoked by at most one thread at a time for an associated
mongoc_client_t or mongoc_client_pool_t object:
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);
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);
mongoc_client_pool_set_oidc_callback (pool, callback);
mongoc_oidc_callback_destroy (callback);
}
// ... client pool operations ...
mongoc_client_pool_destroy (pool);
}
If the callback is associated with more than one mongoc_client_t object
(in multiple threads), or with more than one mongoc_client_pool_t ob-
ject (even in a single thread), the callback function MUST support in-
vocation by more than one thread at a time:
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);
mongoc_client_set_oidc_callback (client_a, callback);
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);
mongoc_client_pool_set_oidc_callback (pool_a, callback);
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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OIDC_CALLBACK_T(3)
mongoc_oidc_credential_destroy.3
MONGOC_OIDC_CREDENTIAL_DESTROY(3) libmongoc MONGOC_OIDC_CREDENTIAL_DESTROY(3)
SYNOPSIS
void
mongoc_oidc_credential_destroy (mongoc_oidc_credential_t *credential)
Release all resources associated with the given
mongoc_oidc_credential_t object.
PARAMETERS
+ credential: a mongoc_oidc_credential_t or NULL.
SEE ALSO:
+ mongoc_oidc_credential_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_OIDC_CREDENTIAL_DESTROY(3)
mongoc_oidc_credential_get_access_token.3
MONGOC_OIDC_CREDENTIAL_GET_ACCESS_TOKEN(3)ocIDC_CREDENTIAL_GET_ACCESS_TOKEN(3)
SYNOPSIS
const char *
mongoc_oidc_credential_get_access_token (const mongoc_oidc_credential_t *cred);
Return the access token stored in the mongoc_oidc_credential_t object.
PARAMETERS
+ cred: a mongoc_oidc_credential_t.
RETURNS
A string which must not be modified or freed.
LIFECYCLE
The string is only valid for the lifetime of the
mongoc_oidc_credential_t object.
SEE ALSO:
+ mongoc_oidc_credential_t
+ mongoc_oidc_callback_fn_t
+ mongoc_oidc_credential_new()
+ mongoc_oidc_credential_new_with_expires_in()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025DC_CREDENTIAL_GET_ACCESS_TOKEN(3)
mongoc_oidc_credential_get_expires_in.3
MONGOC_OIDC_CREDENTIAL_GET_EXPIRES_IN(3)ngoc_OIDC_CREDENTIAL_GET_EXPIRES_IN(3)
SYNOPSIS
const int64_t *
mongoc_oidc_credential_get_expires_in (const mongoc_oidc_credential_t *cred);
Return the optional expiry duration (in milliseconds) for the access
token stored in mongoc_oidc_credential_t.
IMPORTANT:
An unset value is interpreted as an infinite expiry duration.
PARAMETERS
+ cred: a mongoc_oidc_credential_t.
RETURNS
The expiry duration (in milliseconds), or NULL when unset.
LIFECYCLE
The pointed-to int64_t is only valid for the lifetime of the
mongoc_oidc_credential_t object.
SEE ALSO:
+ mongoc_oidc_credential_t
+ mongoc_oidc_credential_new_with_expires_in()
+ mongoc_oidc_callback_fn_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025OIDC_CREDENTIAL_GET_EXPIRES_IN(3)
mongoc_oidc_credential_new.3
MONGOC_OIDC_CREDENTIAL_NEW(3) libmongoc MONGOC_OIDC_CREDENTIAL_NEW(3)
SYNOPSIS
mongoc_oidc_credential_t *
mongoc_oidc_credential_new (const char *access_token)
Create a new mongoc_oidc_credential_t object which stores a copy of the
provided OIDC access token with an infinite expiry duration.
To set a finite expiry duration, use
mongoc_oidc_credential_new_with_expires_in().
WARNING:
access_token is NOT directly validated by the driver.
PARAMETERS
+ access_token: an OIDC access token. Must not be NULL.
RETURNS
A new mongoc_oidc_credential_t that must be freed with
mongoc_oidc_credential_destroy(), or NULL when an invalid argument was
given.
SEE ALSO:
+ mongoc_oidc_credential_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OIDC_CREDENTIAL_NEW(3)
mongoc_oidc_credential_new_with_expires_in.3
MONGOC_OIDC_CREDENTIAL_NEW_WITH_EXPIRESoIN(3)CREDENTIAL_NEW_WITH_EXPIRES_IN(3)
SYNOPSIS
mongoc_oidc_credential_t *
mongoc_oidc_credential_new_with_expires_in (const char *access_token, int64_t expires_in)
Create a new mongoc_oidc_credential_t object which stores a copy of the
provided OIDC access token and its expiry duration (in milliseconds).
The expiry duration will be evaluated relative to the value returned by
System Clock immediately after the callback function has returned.
To set an infinite expiry duration, use mongoc_oidc_credential_new().
WARNING:
access_token is NOT directly validated by the driver.
PARAMETERS
+ access_token: an OIDC access token. Must not be NULL.
+ expires_in: a non-negative integer.
RETURNS
A new mongoc_oidc_credential_t that must be freed with
mongoc_oidc_credential_destroy(), or NULL when an invalid argument was
given.
SEE ALSO:
+ mongoc_oidc_credential_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,O2025CREDENTIAL_NEW_WITH_EXPIRES_IN(3)
mongoc_oidc_credential_t.3
MONGOC_OIDC_CREDENTIAL_T(3) libmongoc MONGOC_OIDC_CREDENTIAL_T(3)
SYNOPSIS
typedef struct _mongoc_oidc_credential_t mongoc_oidc_credential_t;
Represents the return value of a mongoc_oidc_callback_fn_t.
The value will be returned by the mongoc_oidc_callback_fn_t stored in
an mongoc_oidc_callback_t object when it is invoked by an associated
mongoc_client_t or mongoc_client_pool_t object.
RETURN VALUES
The list of currently supported return values are:
+-------------+----------+---------------------+
|Value | Versions | Description |
+-------------+----------+---------------------+
|access_token | 1 | The OIDC access to- |
| | | ken. |
+-------------+----------+---------------------+
|expires_in | 1 | An optional expira- |
| | | tion 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.
Expiry Duration
An optional expiry duration (in milliseconds) for the access token.
IMPORTANT:
An unset value is interpreted as an infinite expiry duration.
SEE ALSO:
+ mongoc_oidc_callback_t
+ mongoc_oidc_callback_fn_t
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OIDC_CREDENTIAL_T(3)
mongoc_optional_copy.3
MONGOC_OPTIONAL_COPY(3) libmongoc MONGOC_OPTIONAL_COPY(3)
SYNOPSIS
void
mongoc_optional_copy (const mongoc_optional_t *source, mongoc_optional_t *copy);
Creates a deep copy of source into copy.
PARAMETERS
+ source: A mongoc_optional_t.
+ copy: An empty mongoc_optional_t. Values will be overwritten.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OPTIONAL_COPY(3)
mongoc_optional_init.3
MONGOC_OPTIONAL_INIT(3) libmongoc MONGOC_OPTIONAL_INIT(3)
SYNOPSIS
void
mongoc_optional_init (mongoc_optional_t *opt);
Initializes values for a mongoc_optional_t.
PARAMETERS
+ opt: A mongoc_optional_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OPTIONAL_INIT(3)
mongoc_optional_is_set.3
MONGOC_OPTIONAL_IS_SET(3) libmongoc MONGOC_OPTIONAL_IS_SET(3)
SYNOPSIS
bool
mongoc_optional_is_set (const mongoc_optional_t *opt);
Returns whether a value for a mongoc_optional_t was set.
PARAMETERS
+ opt: A mongoc_optional_t.
RETURNS
Returns true if a value was set, or false otherwise.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OPTIONAL_IS_SET(3)
mongoc_optional_set_value.3
MONGOC_OPTIONAL_SET_VALUE(3) libmongoc MONGOC_OPTIONAL_SET_VALUE(3)
SYNOPSIS
void
mongoc_optional_set_value (mongoc_optional_t *opt);
Sets a value on a mongoc_optional_t. Once a value has been set, it can-
not be unset, i.e. mongoc_optional_is_set will always return true after
calling mongoc_optional_set_value.
PARAMETERS
+ opt: A mongoc_optional_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OPTIONAL_SET_VALUE(3)
mongoc_optional_t.3
MONGOC_OPTIONAL_T(3) libmongoc MONGOC_OPTIONAL_T(3)
A struct to store optional boolean values.
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 ex-
plicitly set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OPTIONAL_T(3)
mongoc_optional_value.3
MONGOC_OPTIONAL_VALUE(3) libmongoc MONGOC_OPTIONAL_VALUE(3)
SYNOPSIS
bool
mongoc_optional_value (const mongoc_optional_t *opt);
Returns the value for a mongoc_optional_t.
PARAMETERS
+ opt: A mongoc_optional_t.
RETURNS
Returns the value that was set on the mongoc_optional_t. If no value
was set, false is returned.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_OPTIONAL_VALUE(3)
mongoc_query_flags_t.3
MONGOC_QUERY_FLAGS_T(3) libmongoc MONGOC_QUERY_FLAGS_T(3)
Flags for query operations
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. They may be bit-
wise 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_CUR- | Cursor will not be closed |
|SOR | when the last data is re- |
| | trieved. You can resume |
| | this cursor later. |
+---------------------------+----------------------------+
|MONGOC_QUERY_SECONDARY_OK | Allow query of replica set |
| | secondaries. |
+---------------------------+----------------------------+
|MONGOC_QUERY_OPLOG_REPLAY | Used internally by Mon- |
| | goDB. |
+---------------------------+----------------------------+
|MONGOC_QUERY_NO_CUR- | The server normally times |
|SOR_TIMEOUT | out an idle cursor after |
| | an inactivity period (10 |
| | minutes). This prevents |
| | that. |
+---------------------------+----------------------------+
|MONGOC_QUERY_AWAIT_DATA | Use with MON- |
| | GOC_QUERY_TAILABLE_CURSOR. |
| | Block rather than return- |
| | ing no data. After a pe- |
| | riod, time out. |
+---------------------------+----------------------------+
|MONGOC_QUERY_EXHAUST | Unused. |
+---------------------------+----------------------------+
|MONGOC_QUERY_PARTIAL | Get partial results from |
| | mongos if some shards are |
| | down (instead of throwing |
| | an error). |
+---------------------------+----------------------------+
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_QUERY_FLAGS_T(3)
mongoc_rand.3
MONGOC_RAND(3) libmongoc MONGOC_RAND(3)
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 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 spec-
ify 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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_RAND(3)
mongoc_rand_add.3
MONGOC_RAND_ADD(3) libmongoc MONGOC_RAND_ADD(3)
SYNOPSIS
void
mongoc_rand_add (const void *buf, int num, double entropy);
DESCRIPTION
Mixes num bytes of data into the mongoc random number generator. En-
tropy specifies a lower bound estimate of the randomness contained in
buf.
PARAMETERS
+ buf: A buffer.
+ num: An int of number of bytes in buf.
+ entropy: A double of randomness estimate in buf.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_RAND_ADD(3)
mongoc_rand_seed.3
MONGOC_RAND_SEED(3) libmongoc MONGOC_RAND_SEED(3)
SYNOPSIS
void
mongoc_rand_seed (const void *buf, int num);
DESCRIPTION
Seeds the mongoc random number generator with num bytes of entropy.
PARAMETERS
+ buf: A buffer.
+ num: An int of number of bytes in buf.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_RAND_SEED(3)
mongoc_rand_status.3
MONGOC_RAND_STATUS(3) libmongoc MONGOC_RAND_STATUS(3)
SYNOPSIS
int
mongoc_rand_status (void);
DESCRIPTION
The status of the mongoc random number generator.
RETURNS
Returns 1 if the PRNG has been seeded with enough data, 0 otherwise.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_RAND_STATUS(3)
mongoc_read_concern_append.3
MONGOC_READ_CONCERN_APPEND(3) libmongoc MONGOC_READ_CONCERN_APPEND(3)
SYNOPSIS
bool
mongoc_read_concern_append (mongoc_read_concern_t *read_concern, bson_t *opts);
PARAMETERS
+ read_concern: A pointer to a mongoc_read_concern_t.
+ command: A pointer to a bson_t.
DESCRIPTION
This function appends a read concern to command options. It is useful
for appending a read concern to command options before passing them to
mongoc_client_read_command_with_opts() or a related function that takes
an options document.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and logs an error.
EXAMPLE
See the example code for mongoc_client_read_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_CONCERN_APPEND(3)
mongoc_read_concern_copy.3
MONGOC_READ_CONCERN_COPY(3) libmongoc MONGOC_READ_CONCERN_COPY(3)
SYNOPSIS
mongoc_read_concern_t *
mongoc_read_concern_copy (const mongoc_read_concern_t *read_concern);
PARAMETERS
+ read_concern: A mongoc_read_concern_t.
DESCRIPTION
Performs a deep copy of read_concern.
RETURNS
Returns a newly allocated copy of read_concern that should be freed
with mongoc_read_concern_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_CONCERN_COPY(3)
mongoc_read_concern_destroy.3
MONGOC_READ_CONCERN_DESTROY(3) libmongoc MONGOC_READ_CONCERN_DESTROY(3)
SYNOPSIS
void
mongoc_read_concern_destroy (mongoc_read_concern_t *read_concern);
PARAMETERS
+ read_concern: A mongoc_read_concern_t.
DESCRIPTION
Frees all resources associated with the read concern structure. Does
nothing if read_concern is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_CONCERN_DESTROY(3)
mongoc_read_concern_get_level.3
MONGOC_READ_CONCERN_GET_LEVEL(3) libmongoc MONGOC_READ_CONCERN_GET_LEVEL(3)
SYNOPSIS
const char *
mongoc_read_concern_get_level (const mongoc_read_concern_t *read_concern);
PARAMETERS
+ read_concern: A mongoc_read_concern_t.
DESCRIPTION
Returns the currently set read concern.
RETURNS
Returns the current readConcern. If none is set, returns NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_CONCERN_GET_LEVEL(3)
mongoc_read_concern_is_default.3
MONGOC_READ_CONCERN_IS_DEFAULT(3) libmongoc MONGOC_READ_CONCERN_IS_DEFAULT(3)
SYNOPSIS
bool
mongoc_read_concern_is_default (mongoc_read_concern_t *read_concern);
PARAMETERS
+ read_concern: A pointer to a mongoc_read_concern_t.
DESCRIPTION
Returns true if read_concern has not been modified from the default.
For example, if no "readConcern" option is set in the MongoDB URI and
you have not called mongoc_client_set_read_concern(), then
mongoc_read_concern_is_default() is true for the read concern returned
by mongoc_client_get_read_concern().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_READ_CONCERN_IS_DEFAULT(3)
mongoc_read_concern_new.3
MONGOC_READ_CONCERN_NEW(3) libmongoc MONGOC_READ_CONCERN_NEW(3)
SYNOPSIS
mongoc_read_concern_t *
mongoc_read_concern_new (void);
RETURNS
Creates a newly allocated read concern that can be configured based on
user preference. This should be freed with
mongoc_read_concern_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_CONCERN_NEW(3)
mongoc_read_concern_set_level.3
MONGOC_READ_CONCERN_SET_LEVEL(3) libmongoc MONGOC_READ_CONCERN_SET_LEVEL(3)
SYNOPSIS
bool
mongoc_read_concern_set_level (mongoc_read_concern_t *read_concern,
const char *level);
PARAMETERS
+ read_concern: A mongoc_read_concern_t.
+ level: The readConcern level to use.
DESCRIPTION
Sets the read concern level. See mongoc_read_concern_t for details.
Beginning in version 1.9.0, this function can now alter the read con-
cern after it has been used in an operation. Previously, using the
struct with an operation would mark it as "frozen" and calling this
function would return false instead of altering the read concern.
RETURNS
Returns true if the read concern level was set, or false otherwise.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_CONCERN_SET_LEVEL(3)
mongoc_read_concern_t.3
MONGOC_READ_CONCERN_T(3) libmongoc MONGOC_READ_CONCERN_T(3)
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 than NULL.
READ CONCERN LEVELS
+--------------------+---------------------+---------------------+
|Macro | Description | First MongoDB ver- |
| | | sion |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "local", the | 3.2 |
|CERN_LEVEL_LOCAL | default. | |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "majority". | 3.2 |
|CERN_LEVEL_MAJORITY | | |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "lineariz- | 3.4 |
|CERN_LEVEL_LIN- | able". | |
|EARIZABLE | | |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "available". | 3.6 |
|CERN_LEVEL_AVAIL- | | |
|ABLE | | |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "snapshot". | 4.0 |
|CERN_LEVEL_SNAPSHOT | | |
+--------------------+---------------------+---------------------+
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.
See Read Concern Levels in the MongoDB manual for more information
about the individual read concern levels.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_CONCERN_T(3)
mongoc_read_mode_t.3
MONGOC_READ_MODE_T(3) libmongoc MONGOC_READ_MODE_T(3)
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 MON-
GOC_READ_PRIMARY.
Please see the MongoDB website for a description of Read Preferences.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_MODE_T(3)
mongoc_read_prefs_add_tag.3
MONGOC_READ_PREFS_ADD_TAG(3) libmongoc MONGOC_READ_PREFS_ADD_TAG(3)
SYNOPSIS
void
mongoc_read_prefs_add_tag (mongoc_read_prefs_t *read_prefs, const bson_t *tag);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
+ tag: A bson_t.
DESCRIPTION
This function shall add a tag to a read preference.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_ADD_TAG(3)
mongoc_read_prefs_copy.3
MONGOC_READ_PREFS_COPY(3) libmongoc MONGOC_READ_PREFS_COPY(3)
SYNOPSIS
mongoc_read_prefs_t *
mongoc_read_prefs_copy (const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
DESCRIPTION
This function shall deep copy a read preference.
RETURNS
Returns a newly allocated read preference that should be freed with
mongoc_read_prefs_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_COPY(3)
mongoc_read_prefs_destroy.3
MONGOC_READ_PREFS_DESTROY(3) libmongoc MONGOC_READ_PREFS_DESTROY(3)
SYNOPSIS
void
mongoc_read_prefs_destroy (mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
DESCRIPTION
Frees a read preference and all associated resources. Does nothing if
read_prefs is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_DESTROY(3)
mongoc_read_prefs_get_hedge.3
MONGOC_READ_PREFS_GET_HEDGE(3) libmongoc MONGOC_READ_PREFS_GET_HEDGE(3)
Deprecated since version MongoDB: Server 8.0
Hedged reads are deprecated in MongoDB version 8.0 and will be removed in a
future release.
SYNOPSIS
const bson_t *
mongoc_read_prefs_get_hedge (const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
DESCRIPTION
Fetches any read preference hedge document that has been registered.
RETURNS
Returns a bson_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_GET_HEDGE(3)
mongoc_read_prefs_get_max_staleness_seconds.3
MONGOC_READ_PREFS_GET_MAX_STALENESSlSECONDS(3)EFS_GET_MAX_STALENESS_SECONDS(3)
SYNOPSIS
int64_t
mongoc_read_prefs_get_max_staleness_seconds (
const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
DESCRIPTION
Clients estimate the staleness of each secondary, and select for reads
only those secondaries whose estimated staleness is less than or equal
to maxStalenessSeconds. The default is MONGOC_NO_MAX_STALENESS.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,E2025REFS_GET_MAX_STALENESS_SECONDS(3)
mongoc_read_prefs_get_mode.3
MONGOC_READ_PREFS_GET_MODE(3) libmongoc MONGOC_READ_PREFS_GET_MODE(3)
SYNOPSIS
mongoc_read_mode_t
mongoc_read_prefs_get_mode (const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
DESCRIPTION
Fetches the mongoc_read_mode_t for the read preference.
RETURNS
Returns the read preference mode.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_GET_MODE(3)
mongoc_read_prefs_get_tags.3
MONGOC_READ_PREFS_GET_TAGS(3) libmongoc MONGOC_READ_PREFS_GET_TAGS(3)
SYNOPSIS
const bson_t *
mongoc_read_prefs_get_tags (const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
DESCRIPTION
Fetches any read preference tags that have been registered.
RETURNS
Returns a bson_t that should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_GET_TAGS(3)
mongoc_read_prefs_is_valid.3
MONGOC_READ_PREFS_IS_VALID(3) libmongoc MONGOC_READ_PREFS_IS_VALID(3)
SYNOPSIS
bool
mongoc_read_prefs_is_valid (const mongoc_read_prefs_t *read_prefs);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
DESCRIPTION
Performs a consistency check of read_prefs to ensure it makes sense and
can be satisfied.
This only performs local consistency checks.
RETURNS
Returns true if the read pref is valid.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_IS_VALID(3)
mongoc_read_prefs_new.3
MONGOC_READ_PREFS_NEW(3) libmongoc MONGOC_READ_PREFS_NEW(3)
SYNOPSIS
mongoc_read_prefs_t *
mongoc_read_prefs_new (mongoc_read_mode_t read_mode);
PARAMETERS
+ read_mode: A mongoc_read_mode_t.
DESCRIPTION
Creates a new mongoc_read_prefs_t using the mode specified.
RETURNS
Returns a newly allocated mongoc_read_prefs_t that should be freed with
mongoc_read_prefs_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_NEW(3)
mongoc_read_prefs_set_hedge.3
MONGOC_READ_PREFS_SET_HEDGE(3) libmongoc MONGOC_READ_PREFS_SET_HEDGE(3)
Deprecated since version MongoDB: Server 8.0
Hedged reads are deprecated in MongoDB version 8.0 and will be removed in a
future release.
SYNOPSIS
void
mongoc_read_prefs_set_hedge (mongoc_read_prefs_t *read_prefs,
const bson_t *hedge);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
+ hedge: A bson_t.
DESCRIPTION
Sets the hedge document to be used for the read preference. Sharded
clusters running MongoDB 4.4 or later can dispatch read operations in
parallel, returning the result from the fastest host and cancelling the
unfinished operations.
For example, this is a valid hedge document
{
enabled: true
}
Appropriate values for the enabled key are true or false.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_SET_HEDGE(3)
mongoc_read_prefs_set_max_staleness_seconds.3
MONGOC_READ_PREFS_SET_MAX_STALENESSlSECONDS(3)EFS_SET_MAX_STALENESS_SECONDS(3)
SYNOPSIS
void
mongoc_read_prefs_set_max_staleness_seconds (mongoc_read_prefs_t *read_prefs,
int64_t max_staleness_seconds);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
+ max_staleness_seconds: A positive integer or MONGOC_NO_MAX_STALENESS.
DESCRIPTION
Sets the maxStalenessSeconds to be used for the read preference.
Clients estimate the staleness of each secondary, and select for reads
only those secondaries whose estimated staleness is less than or equal
to maxStalenessSeconds.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,E2025REFS_SET_MAX_STALENESS_SECONDS(3)
mongoc_read_prefs_set_mode.3
MONGOC_READ_PREFS_SET_MODE(3) libmongoc MONGOC_READ_PREFS_SET_MODE(3)
SYNOPSIS
void
mongoc_read_prefs_set_mode (mongoc_read_prefs_t *read_prefs,
mongoc_read_mode_t mode);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
+ mode: A mongoc_read_mode_t.
DESCRIPTION
Sets the read preference mode. See the MongoDB website for more infor-
mation on Read Preferences.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_SET_MODE(3)
mongoc_read_prefs_set_tags.3
MONGOC_READ_PREFS_SET_TAGS(3) libmongoc MONGOC_READ_PREFS_SET_TAGS(3)
SYNOPSIS
void
mongoc_read_prefs_set_tags (mongoc_read_prefs_t *read_prefs,
const bson_t *tags);
PARAMETERS
+ read_prefs: A mongoc_read_prefs_t.
+ tags: A bson_t.
DESCRIPTION
Sets the tags to be used for the read preference. Only mongod instances
matching these tags will be suitable for handling the request.
EXAMPLES
#include <mongoc/mongoc.h>
static void
run_query_with_read_prefs_tags (mongoc_collection_t *collection)
{
char *str;
const bson_t *doc;
bson_t filter = BSON_INITIALIZER;
bson_error_t error;
mongoc_cursor_t *cursor;
mongoc_read_prefs_t *read_prefs;
/* Create a tagset representing
* [
* {"dc": "ny", "rack": "1" }, // Any node in rack1 in the ny datacenter
* {"dc": "ny", "rack": "2" }, // Any node in rack2 in the ny datacenter
* {"dc": "ny" }, // Any node in the ny datacenter
* {} // If all else fails, just any available node
* ]
*/
bson_t *tags = BCON_NEW (
"0", "{", "dc", BCON_UTF8("ny"), "rack", BCON_UTF8("1"), "}",
"1", "{", "dc", BCON_UTF8("ny"), "rack", BCON_UTF8("2"), "}",
"2", "{", "dc", BCON_UTF8("ny"), "}",
"3", "{", "}"
);
read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
mongoc_read_prefs_set_tags (read_prefs, tags);
bson_destroy (tags);
cursor =
mongoc_collection_find_with_opts (collection, &filter, NULL, read_prefs);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_canonical_extended_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
if (mongoc_cursor_error (cursor, &error)) {
fprintf (stderr, "Cursor error: %s\n", error.message);
}
mongoc_cursor_destroy (cursor);
mongoc_read_prefs_destroy (read_prefs);
bson_destroy (doc);
}
int main (void)
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost/?appname=rp_tags&replicaSet=foo");
mongoc_client_set_error_api (client, 2);
collection = mongoc_client_get_collection (client, "dbname", "collname");
run_query_with_read_prefs_tags (collection);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup();
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_SET_TAGS(3)
mongoc_read_prefs_t.3
MONGOC_READ_PREFS_T(3) libmongoc MONGOC_READ_PREFS_T(3)
A read preference abstraction
SYNOPSIS
mongoc_read_prefs_t provides an abstraction on top of the MongoDB con-
nection read preferences. It allows for hinting to the driver which
nodes in a replica set should be accessed first and how.
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.
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 opera- |
| | tions read from the cur- |
| | rent replica set primary. |
+---------------------------+----------------------------+
|MONGOC_READ_SECONDARY | All operations read from |
| | among the nearest sec- |
| | ondary members of the |
| | replica set. |
+---------------------------+----------------------------+
|MONGOC_READ_PRIMARY_PRE- | In most situations, opera- |
|FERRED | tions read from the pri- |
| | mary but if it is unavail- |
| | able, operations read from |
| | secondary members. |
+---------------------------+----------------------------+
|MONGOC_READ_SECONDARY_PRE- | In most situations, opera- |
|FERRED | tions 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 con-
cerns so that your application can target operations to specific mem-
bers.
Custom read preferences and write concerns evaluate tags sets in dif-
ferent ways: read preferences consider the value of a tag when select-
ing a member to read from, while 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.
However, the nearest read mode, when combined with a tag set, will se-
lect 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, using multiple readPreferenceTags, e.g.
readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=
Note the empty value for the last one, which means "match any secondary
as a last resort".
Order matters when using multiple readPreferenceTags.
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 prefer-
ence 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 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.
Otherwise, it must be a positive integer at least MONGOC_SMALL-
EST_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.
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.
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 dis-
abled 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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_READ_PREFS_T(3)
mongoc_reference.3
MONGOC_REFERENCE(3) libmongoc MONGOC_REFERENCE(3)
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 depends on libbson to generate and parse BSON documents, the native
data format of MongoDB.
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.
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 re-
lease 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().
Changed in version 2.0.0: Versions prior to 2.0.0 supported a non-por-
table automatic initialization and cleanup with the CMake option EN-
ABLE_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.
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.
Macros
To make logging a little less painful, various helper macros are pro-
vided. 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 std-
out, or to stderr for warnings, critical messages, and errors. You can
override the handler with mongoc_log_set_handler(). Your handler func-
tion 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_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 be-
fore 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 er-
rors, provide an empty log handler:
mongoc_log_set_handler (NULL, NULL);
Tracing
If compiling your own copy of the MongoDB C driver, consider configur-
ing with -DENABLE_TRACING=ON to enable function tracing and hex dumps
of network packets to STDERR and STDOUT during development and debug-
ging.
This is especially useful when debugging what may be going on inter-
nally in the driver.
Trace messages can be enabled and disabled by calling mon-
goc_log_trace_enable() and mongoc_log_trace_disable()
NOTE:
Compiling the driver with -DENABLE_TRACING=ON will affect its per-
formance. Disabling tracing with mongoc_log_trace_disable() signifi-
cantly reduces the overhead, but cannot remove it completely.
Structured Logging
This document describes a newer "structured" logging facility which re-
ports 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().
Options
Structured log settings are tracked explicitly by a
mongoc_structured_log_opts_t instance.
Like other drivers supporting structured logging, we take default set-
tings from environment variables and offer additional optional program-
matic 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 pro-
grammatic 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 han-
dler, 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 maxi-
mum 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().
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 cap-
tured 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 warn-
ings 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 implementa-
tion-specific value near the maximum representable length. By de-
fault, the limit is 1000 bytes. This limit affects interior docu-
ments 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:
When a file path is given for MONGODB_LOG_PATH, each log instance
(one stand-alone client or pool) will separately open this file
for append. The results are operating system specific. On
UNIX-like platforms each instance's output will be interleaved, in
most cases without splitting individual log messages. Notably on
Windows the file will be opened in exclusive mode by the first in-
stance and subsequent instances will fail, falling back on the de-
fault of stderr. Applications that use multiple processes or mul-
tiple client pools will likely want to supply a log handler that
annotates each message with information about its originating log
instance.
+ MONGODB_LOG_COMMAND: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_COMMAND.
+ MONGODB_LOG_TOPOLOGY: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_TOPOLOGY.
+ MONGODB_LOG_SERVER_SELECTION: A log level name to set as the maximum
for MONGOC_STRUCTURED_LOG_COMPONENT_SERVER_SELECTION.
+ MONGODB_LOG_CONNECTION: A log level name to set as the maximum for
MONGOC_STRUCTURED_LOG_COMPONENT_CONNECTION.
+ MONGODB_LOG_ALL: A log level name applied to all components not oth-
erwise specified.
Note that log level names are always case insensitive. This is a full
list of recognized names, including allowed aliases:
+ 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 allocated with
mongoc_structured_log_opts_new(), or NULL.
Description
This function releases all resources associated with a
mongoc_structured_log_opts_t. Does nothing if opts is NULL.
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 to be called to handle structured log messages, as a
mongoc_structured_log_func_t.
The callback is given a mongoc_structured_log_entry_t as a handle for
obtaining additional information about the log message. This entry
pointer is only valid during a callback, because it's a low cost refer-
ence to temporary data.
Structured log handlers must be thread-safe if they will be used with
mongoc_client_pool_t. Handlers must avoid unbounded recursion, prefer-
ably by avoiding the use of any libmongoc client or pool which uses the
same handler.
This function always replaces the default log handler from
mongoc_structured_log_opts_new(), if it was still set. If the log_func
is set to NULL, structured logging will be disabled.
Parameters
+ opts: Structured log options, allocated with
mongoc_structured_log_opts_new().
+ log_func: The handler to install, a mongoc_structured_log_func_t, or
NULL to disable structured logging.
+ user_data: Optional user data, passed on to the 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 be-
low this severity level will be passed to mongoc_structured_log_func_t.
By default, each component's log level may come from environment vari-
ables. 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 to set 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 supplied parameters were in-
correct.
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 all per-component maximum log levels to the same value. Only log
messages at or below this severity level will be passed to
mongoc_structured_log_func_t. Effective even for logging components
not known at compile-time.
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 in-
correct.
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 requested by environment variables: MON-
GODB_LOG_ALL for all components, followed by per-component log levels
MONGODB_LOG_COMMAND, MONGODB_LOG_CONNECTION, MONGODB_LOG_TOPOLOGY, and
MONGODB_LOG_SERVER_SELECTION.
Expects the value to be recognizable by
mongoc_structured_log_get_named_level(). Parse errors may cause a
warning message, delivered via unstructured logging.
Component levels with no valid environment variable setting will be
left unmodified.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may 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(). This
will process the environment a second time, allowing it to override
customized defaults.
Returns
Returns true on success. If warnings are encountered in the environ-
ment, returns false and may log additional information to the unstruc-
tured logging facility. Note that, by design, these errors are by de-
fault 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_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 a specific component, as a
mongoc_structured_log_level_t. This may 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
may be the default obtained from environment variables. If an invalid
or unknown component enum is given, returns the lowest log level.
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 appear serialized in JSON
form as part of a structured log message.
Serialized JSON will be truncated at this limit, interpreted as a count
of UTF-8 encoded bytes. Truncation will be indicated with a ... suffix,
the length of which is not included in the max document length. If
truncation at the exact indicated length would split a valid UTF-8 se-
quence, we instead truncate the document earlier at the nearest bound-
ary between code points.
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 trunca-
tion. Values near or above INT_MAX will be rejected.
Returns
Returns true on success, or false if the supplied maximum length 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 a description of the supported en-
vironment variable formats.
Parse errors may cause a warning message, delivered via unstructured
logging.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may call
mongoc_structured_log_opts_set_max_document_length_from_env() after
calling mongoc_structured_log_opts_set_max_document_length(). This
will process the environment a second time, allowing it to override
customized defaults.
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 de-
sign, these errors are by default non-fatal. When
mongoc_structured_log_opts_new() internally calls this function, it ig-
nores 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 set in opts, as a size_t.
SEE ALSO:
Structured Logging
SEE ALSO:
Structured Logging
Levels and Components
Log levels and components are defined as mongoc_structured_log_level_t
and mongoc_structured_log_component_t enumerations. Utilities are pro-
vided to convert between these values and their standard string repre-
sentations. The string values are case-insensitive.
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 the available log levels for
use with structured logging.
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, returns a pointer to a constant string that
should not be freed. If the level has no known name, 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.
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, returns true and writes the level enum to
*out. If the level name is not known, returns false and does not write
*out.
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. Applications should never rely on having an exhaustive
list of all log components. Instead, use
mongoc_structured_log_opts_set_max_level_for_all_components() to set a
default level if needed.
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.
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, returns true and writes the component
enum to *out. If the component name is not known, returns false and
does not write *out.
SEE ALSO:
Structured Logging
SEE ALSO:
Structured Logging
SEE ALSO:
mongoc_structured_log_get_level_name mongoc_struc-
tured_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 in-
stance of the structured logging subsystem, with its own settings and
handler.
When using mongoc_client_pool_t, the pooled clients all share a common
logging instance. Handlers must be thread-safe.
The handler is called for each log entry with a level no greater than
its component's maximum. A mongoc_structured_log_entry_t pointer pro-
vides access to further details, during the handler only.
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.
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(). Struc-
tured log handlers must be thread-safe if they will be used with
mongoc_client_pool_t. Handlers must avoid unbounded recursion, prefer-
ably by avoiding the use of any libmongoc client or pool which uses the
same handler.
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 within the handler by a short-lived
mongoc_structured_log_entry_t pointer. During the handler, this
pointer can be used to access the individual properties of an entry:
its level, component, and message.
The message will be assembled as a bson_t only when explicitly re-
quested by a call to mongoc_structured_log_entry_message_as_bson().
This results in a standalone document that may be retained for any
amount of time and must be explicitly destroyed.
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 which represents
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 individual aspects
of the log entry.
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 struc-
tured log handler. It should not be freed or modified.
Identical to the value of the message key in the document returned by
mongoc_structured_log_entry_message_as_bson().
This is not a complete string representation of the structured log, but
rather a standardized identifier for a particular log event.
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 rep-
resentation. When possible, a log handler should avoid serializing log
messages that will be discarded. 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
/* 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 proceses 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_en-
try_get_level mongoc_structured_log_entry_message_as_bson
<< libmongoc - API
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 er-
ror, and code for the specific error. message is a human-readable error
description.
SEE ALSO:
Handling Errors in libbson.
+--------------------+----------------------------------+--------------------------------------------+
|Code | Description | |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_CLIENT | MONGOC_ER- | You tried to send a |
| | ROR_CLIENT_TOO_BIG | message larger than |
| | | the server's max |
| | | message size. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Wrong credentials, |
| | ROR_CLIENT_AUTHEN- | or failure sending |
| | TICATE | or receiving au- |
| | | thentication mes- |
| | | sages. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | You tried an TLS |
| | ROR_CLIENT_NO_AC- | connection but the |
| | CEPTABLE_PEER | driver was not |
| | | built with TLS. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | You began iterating |
| | ROR_CLIENT_IN_EX- | an exhaust cursor, |
| | HAUST | then tried to begin |
| | | another operation |
| | | with the same |
| | | mongoc_client_t. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Failure related to |
| | ROR_CLIENT_SES- | creating or using a |
| | SION_FAILURE | logical session. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Failure related to |
| | ROR_CLIENT_IN- | arguments passed |
| | VALID_ENCRYP- | when initializing |
| | TION_ARG | In-Use Encryption. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Failure related to |
| | ROR_CLIENT_IN- | In-Use Encryption. |
| | VALID_ENCRYP- | |
| | TION_STATE | |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | You attempted to |
| | ROR_CLIENT_IN- | connect to a Mon- |
| | VALID_LOAD_BALANCER | goDB server behind |
| | | a load balancer, |
| | | but the server does |
| | | not advertize load |
| | | balanced support. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | You attempted to |
| | ROR_CLIENT_NOT_READY | create a client but |
| | | did not previously |
| | | call mongoc_init() |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_STREAM | MONGOC_ER- | DNS failure. |
| | ROR_STREAM_NAME_RES- | |
| | OLUTION | |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Timeout communicat- |
| | ROR_STREAM_SOCKET | ing with server, or |
| | | connection closed. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | Failed to connect |
| | ROR_STREAM_CONNECT | to server. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_PROTO- | MONGOC_ERROR_PROTO- | Corrupt response |
|COL | COL_INVALID_REPLY | from server. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_PROTO- | The server version |
| | COL_BAD_WIRE_VERSION | is too old or too |
| | | new to communicate |
| | | with the driver. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_CURSOR | MONGOC_ERROR_CUR- | You passed bad ar- |
| | SOR_INVALID_CURSOR | guments 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_ER- | A resume token was not returned in |
| | ROR_CHANGE_STREAM_NO_RE- | a document found with |
| | SUME_TOKEN | mongoc_change_stream_next() |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_QUERY | MONGOC_ERROR_QUERY_FAIL- | Error API Version 1: Server error |
| | URE | from command or query. The server |
| | | error message is in message. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_SERVER | MONGOC_ERROR_QUERY_FAIL- | Error API Version 2: Server error |
| | URE | 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_IN- | You passed an invalid or oversized |
| | VALID | BSON document as a parameter or the |
| | | server reply was corrupt. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_NAME- | MONGOC_ERROR_NAME- | You tried to create a collection |
|SPACE | SPACE_INVALID | with an invalid name. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_COM- | MONGOC_ERROR_COMMAND_IN- | Many functions set this error code |
|MAND | VALID_ARG | when passed bad parameters. Print |
| | | the error message for details. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_PROTO- | You tried to use a command option |
| | COL_BAD_WIRE_VERSION | the server does not support. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_DUPLI- | An insert or update failed because |
| | CATE_KEY | because of a duplicate _id or other |
| | | unique-index violation. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | The operation failed because max- |
| | ROR_MAX_TIME_MS_EXPIRED | TimeMS expired. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_SERVER_SE- | The serverId option for an opera- |
| | LECTION_INVALID_ID | tion conflicts with the pinned |
| | | server for that operation's client |
| | | session (denoted by the sessionId |
| | | option). |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_COM- | Error code from server. | Error API Version 1: Server error |
|MAND | | 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_COL- | MONGOC_ERROR_COLLEC- | Invalid or empty input to |
|LECTION | TION_INSERT_FAILED, MON- | mongoc_collection_insert_one(), |
| | GOC_ERROR_COLLECTION_UP- | mongoc_collection_insert_many(), |
| | DATE_FAILED, MONGOC_ER- | mongoc_collection_update_one(), |
| | ROR_COLLEC- | mongoc_collection_update_many(), |
| | TION_DELETE_FAILED. | mongoc_collection_replace_one(), |
| | | mongoc_collection_delete_one(), or |
| | | mongoc_collection_delete_many(). |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_COL- | Error code from server. | Error API Version 1: Server error |
|LECTION | | 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(), |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_GRIDFS | MONGOC_ER- | The GridFS file is missing a docu- |
| | ROR_GRIDFS_CHUNK_MISSING | ment in its chunks collection. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_GRIDFS_COR- | A data inconsistency was detected |
| | RUPT | in GridFS. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_GRIDFS_IN- | You passed a NULL filename to |
| | VALID_FILENAME | mongoc_gridfs_remove_by_filename(). |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ERROR_GRIDFS_PRO- | You called |
| | TOCOL_ERROR | mongoc_gridfs_file_set_id() after |
| | | mongoc_gridfs_file_save(), or tried |
| | | to write on a closed GridFS stream. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | A GridFS file is missing from files |
| | ROR_GRIDFS_BUCKET_FILE_NOT_FOUND | collection. |
+--------------------+----------------------------------+--------------------------------------------+
| | MONGOC_ER- | An error occurred on a stream cre- |
| | ROR_GRIDFS_BUCKET_STREAM | ated from a GridFS operation like |
| | | mongoc_gridfs_bucket_upload_from_stream(). |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_SCRAM | MONGOC_ERROR_SCRAM_PROTOCOL_ER- | Failure in SCRAM-SHA-1 or SCRAM-SHA-256 |
| | ROR | authentication. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ER- | MONGOC_ERROR_SERVER_SELEC- | No replica set member or mongos is avail- |
|ROR_SERVER_SELEC- | TION_FAILURE | able, or none matches your read prefer- |
|TION | | ence, or you supplied an invalid |
| | | mongoc_read_prefs_t. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ER- | Error code from server. | There was a write concern error or timeout |
|ROR_WRITE_CONCERN | | from the server. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ERROR_TRANS- | MONGOC_ERROR_TRANSACTION_INVALID | You attempted to start a transaction when |
|ACTION | | one is already in progress, or commit or |
| | | abort when there is no transaction. |
+--------------------+----------------------------------+--------------------------------------------+
|MONGOC_ER- | Error code produced by libmon- | An error occurred in the library responsi- |
|ROR_CLIENT_SIDE_EN- | gocrypt. | ble for In-Use Encryption |
|CRYPTION | | |
+--------------------+----------------------------------+--------------------------------------------+
|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 |
+--------------------+----------------------------------+--------------------------------------------+
|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 |
+--------------------+----------------------------------+--------------------------------------------+
Error Labels
In some cases your application must make decisions based on what cate-
gory of error the driver has returned, but these categories do not cor-
respond perfectly to an error domain or code. In such cases, error la-
bels provide a reliable way to determine how your application should
respond to an error.
Any C Driver function that has a bson_t out-parameter named reply may
include error labels to the reply, in the form of a BSON field named
"errorLabels" containing an array of strings:
{ "errorLabels": [ "TransientTransactionError" ] }
Use mongoc_error_has_label() to test if a reply contains a specific la-
bel. See mongoc_client_session_start_transaction() for example code
that demonstrates the use of error labels in application logic.
The following error labels are currently defined. Future versions of
MongoDB may introduce new labels.
TransientTransactionError
Within a multi-document transaction, certain errors can leave the
transaction in an unknown or aborted state. These include write con-
flicts, primary stepdowns, and network errors. In response, the appli-
cation should abort the transaction and try the same sequence of opera-
tions again in a new transaction.
UnknownTransactionCommitResult
When mongoc_client_session_commit_transaction() encounters a network
error or certain server errors, it is not known whether the transaction
was committed. Applications should attempt to commit the transaction
again until: the commit succeeds, the commit fails with an error not
labeled "UnknownTransactionCommitResult", or the application chooses to
give up.
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_ER-
ROR_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_one() 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_COLLEC-
TION_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 do-
main, MONGOC_ERROR_SERVER. In Version 2, error codes originating on the
server always have error domain MONGOC_ERROR_SERVER or MONGOC_ER-
ROR_WRITE_CONCERN. When the driver uses Version 2 the application can
always determine the origin and meaning of error codes. New applica-
tions 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_with_opts(), | MONGOC_ERROR_QUERY | MONGOC_ERROR_SERVER |
|mongoc_database_command_with_opts(), | | |
|and other command | | |
|functions | | |
+---------------------------------------------+--------------------+---------------------+
|mongoc_client_get_database_names_with_opts() | MONGOC_ERROR_QUERY | MONGOC_ERROR_SERVER |
|and other command helper functions | | |
+---------------------------------------------+--------------------+---------------------+
|mongoc_collection_insert_one() | MONGOC_ERROR_COM- | MONGOC_ERROR_SERVER |
|mongoc_collection_insert_many() | MAND | |
|mongoc_collection_update_one() | | |
|mongoc_collection_update_many() | | |
|mongoc_collection_replace_one() | | |
|mongoc_collection_delete_one() | | |
|mongoc_collection_delete_many() | | |
+---------------------------------------------+--------------------+---------------------+
|mongoc_bulk_operation_execute() | MONGOC_ERROR_COM- | MONGOC_ERROR_SERVER |
| | MAND | |
+---------------------------------------------+--------------------+---------------------+
|Write-concern timeout | MONGOC_ER- | MONGOC_ER- |
| | ROR_WRITE_CONCERN | ROR_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
Object Lifecycle
This page documents the order of creation and destruction for libmon-
goc'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 ac-
quires a mongoc_client_t from the pool with mongoc_client_pool_pop()
and returns it with mongoc_client_pool_push() when the thread is fin-
ished 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.
GridFS bucket objects
Create mongoc_gridfs_bucket_t with a mongoc_database_t derived from a
mongoc_client_t. The mongoc_database_t is independent from the
mongoc_gridfs_bucket_t. But the mongoc_client_t must outlive the
mongoc_gridfs_bucket_t.
A mongoc_stream_t may be created from the mongoc_gridfs_bucket_t. The
mongoc_gridfs_bucket_t must outlive the mongoc_stream_t.
Sessions
Start a session with mongoc_client_start_session(), use the 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.
By default, sessions are causally consistent. To disable causal consis-
tency, 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 ses-
sion 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.
Client Side Encryption
When 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 (via
mongoc_auto_encryption_opts_set_keyvault_client()) the key vault client
must outlive the encrypted client.
When 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()) the key vault
client pool must outlive the encrypted client pool.
When 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.
GridFS
The C driver includes two APIs for GridFS.
The older API consists of mongoc_gridfs_t and its derivatives. It con-
tains deprecated API, does not support read preferences, and is not
recommended in new applications. It does not conform to the MongoDB
GridFS specification.
The newer API consists of mongoc_gridfs_bucket_t and allows upload-
ing/downloading through derived mongoc_stream_t objects. It conforms to
the MongoDB GridFS specification.
There is not always a straightforward upgrade path from an application
built with mongoc_gridfs_t to mongoc_gridfs_bucket_t (e.g. a
mongoc_gridfs_file_t provides functions to seek but mongoc_stream_t
does not). But users are encouraged to upgrade when possible.
mongoc_auto_encryption_opts_t
Options for enabling automatic encryption and decryption for In-Use En-
cryption.
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.
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.
NOTE:
If using MongoDB server 8.0+, prefer mongoc_bulkwrite_t over
mongoc_bulk_operation_t to reduce network round trips.
mongoc_bulkwrite_t uses the bulkWrite server command introduced in
MongoDB server 8.0. bulkWrite command supports insert, update, and
delete operations in the same payload. bulkWrite supports use of
multiple collection namespaces in the same payload.
mongoc_bulk_operation_t uses the insert, update and delete server
commands available in all current MongoDB server versions. Write op-
erations 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_bulk_operation_t
Bulk Write Operations
Synopsis
typedef struct _mongoc_bulk_operation_t mongoc_bulk_operation_t;
Description
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 exe-
cute 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_bulkwrite_t
NOTE:
If using MongoDB server 8.0+, prefer mongoc_bulkwrite_t over
mongoc_bulk_operation_t to reduce network round trips.
mongoc_bulkwrite_t uses the bulkWrite server command introduced in
MongoDB server 8.0. bulkWrite command supports insert, update, and
delete operations in the same payload. bulkWrite supports use of
multiple collection namespaces in the same payload.
mongoc_bulk_operation_t uses the insert, update and delete server
commands available in all current MongoDB server versions. Write op-
erations are grouped by type (insert, update, delete) and sent in
separate commands. Only one collection may be specified per bulk
write.
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 in-
stead of a raw aggregation with a $changeStream stage. For more infor-
mation see the MongoDB Manual Entry on Change Streams.
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: %s\n"
"error message: %s\n",
uri_string,
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.
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.
Additionally, change streams can start returning changes at an opera-
tion 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 exclu-
sive options. Setting more than one will result in a server error.
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: %s\n"
"error message: %s\n",
uri_string,
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;
}
The following example shows using startAtOperationTime to synchronize a
change stream with another operation.
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: %s\n"
"error message: %s\n",
uri_string,
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;
}
mongoc_client_encryption_t
Synopsis
typedef struct _mongoc_client_encryption_t mongoc_client_encryption_t;
mongoc_client_encryption_t provides utility functions for In-Use En-
cryption.
Thread Safety
mongoc_client_encryption_t is NOT thread-safe and should only be used
in the same thread as the mongoc_client_t that is configured via
mongoc_client_encryption_opts_set_keyvault_client().
Lifecycle
The key vault client, configured via
mongoc_client_encryption_opts_set_keyvault_client(), must outlive the
mongoc_client_encryption_t.
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;
Used to set options for mongoc_client_encryption_create_datakey().
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;
Used to access the result of
mongoc_client_encryption_rewrap_many_datakey().
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;
Used to set options for mongoc_client_encryption_encrypt().
SEE ALSO:
mongoc_client_encryption_encrypt()
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 sup-
porting "range" queries. Used to set options for
mongoc_client_encryption_encrypt().
The options min, max, trim factor, sparsity, and range must match the
values set in the encryptedFields of the destination collection.
For double and decimal128 fields, min/max/precision must all be set, or
all be unset.
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;
Used to set options for mongoc_client_encryption_new().
SEE ALSO:
mongoc_client_encryption_new()
mongoc_client_pool_t
A connection pool for multi-threaded programs. See Connection Pooling.
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, except for its destructor method,
mongoc_client_pool_destroy(), which is not thread-safe and must only be
called from one thread.
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: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
pool = mongoc_client_pool_new (uri);
mongoc_client_pool_set_error_api (pool, 2);
for (i = 0; i < 10; i++) {
pthread_create (&threads[i], NULL, worker, pool);
}
sleep (10);
pthread_mutex_lock (&mutex);
in_shutdown = true;
pthread_mutex_unlock (&mutex);
for (i = 0; i < 10; i++) {
pthread_join (threads[i], &ret);
}
mongoc_client_pool_destroy (pool);
mongoc_uri_destroy (uri);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
mongoc_client_session_t
Use a session for a sequence of operations, optionally with causal con-
sistency. See the MongoDB Manual Entry for Causal Consistency.
Synopsis
Start a session with mongoc_client_start_session(), use the 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.
By default, sessions are causally consistent. To disable causal consis-
tency, 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 ses-
sion 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.
Fork Safety
A mongoc_client_session_t is only usable in the parent process after a
fork. The child process must call mongoc_client_reset() on the client
field.
Example
example-session.c
/* gcc example-session.c -o example-session \
* $(pkg-config --cflags --libs libmongoc-1.0) */
/* ./example-session [CONNECTION_STRING] */
#include <stdio.h>
#include <mongoc/mongoc.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: %s\n"
"error message: %s\n",
uri_string,
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);
Provide this callback to mongoc_client_session_with_transaction(). The
callback should run a sequence of operations meant to be contained
within a transaction. The callback should not attempt to start or com-
mit transactions.
Parameters
+ session: A mongoc_client_session_t.
+ ctx: A void* set to the the user-provided ctx passed to
mongoc_client_session_with_transaction().
+ 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.
SEE ALSO:
mongoc_client_session_with_transaction()
mongoc_client_t
A single-threaded MongoDB connection. See Connection Pooling.
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
server, replica set, or sharded cluster. It maintains management of un-
derlying 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 cus-
tom 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 recom-
mended that you use the thread-safe mongoc_client_pool_t to retrieve a
mongoc_client_t for your thread.
Fork Safety
A mongoc_client_t is only usable in the parent process after a fork.
The child process must call mongoc_client_reset().
Example
example-client.c
/* 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: %s\n"
"error message: %s\n",
uri_string,
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 provides access to a MongoDB collection. This han-
dle is useful for actions for most CRUD operations, I.e. insert, up-
date, 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.
mongoc_cursor_t
Client-side cursor abstraction
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.
Common cursor operations include:
+ 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().
Cursors are lazy, meaning that no connection is established and no net-
work traffic occurs until the first call to mongoc_cursor_next().
Thread Safety
mongoc_cursor_t is NOT thread safe. It may only be used from within the
thread in which it was created.
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: %s\n"
"error message: %s\n",
uri_string,
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 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().
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 to construct the
findAndModify command.
It was created to be able to accommodate new arguments to the findAnd-
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
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);
}
opts.c
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);
}
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: %s\n"
"error message: %s\n",
uri_string,
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;
}
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/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_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 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, meta-
data, 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_bucket_t
Synopsis
#include <mongoc/mongoc.h>
typedef struct _mongoc_gridfs_bucket_t mongoc_gridfs_bucket_t;
Description
mongoc_gridfs_bucket_t provides a spec-compliant MongoDB GridFS imple-
mentation, superseding mongoc_gridfs_t. See the GridFS MongoDB documen-
tation.
Thread Safety
mongoc_gridfs_bucket_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_bucket_t before freeing all de-
rived instances of mongoc_stream_t. The owning mongoc_client_t must
outlive the mongoc_gridfs_bucket_t.
Example
example-gridfs-bucket.c
#include <stdio.h>
#include <stdlib.h>
#include <mongoc/mongoc.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;
}
/* 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;
}
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.
Synopsis
#include <mongoc/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 prac-
tical 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 ex-
isting gridfs object, just use them with caution.
mongoc_gridfs also integrates tightly with the mongoc_stream_t abstrac-
tion, 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 in-
stances of mongoc_gridfs_file_t and mongoc_gridfs_file_list_t.
Example
example-gridfs.c
#include <assert.h>
#include <mongoc/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;
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: %s\n"
"error message: %s\n",
uri_string,
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) {
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 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.
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_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 bit-
wise or'd together. They may modify how an insert happens on the Mon-
goDB server.
Flag Values
+--------------------------+----------------------------+
|MONGOC_INSERT_NONE | Specify no insert flags. |
+--------------------------+----------------------------+
|MONGOC_INSERT_CON- | Continue inserting docu- |
|TINUE_ON_ERROR | ments from the insertion |
| | set even if one insert |
| | fails. |
+--------------------------+----------------------------+
|MONGOC_INSERT_NO_VALIDATE | Do not validate insertion |
| | documents before perform- |
| | ing 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/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_oidc_callback_fn_t
Synopsis
typedef mongoc_oidc_credential_t *(*mongoc_oidc_callback_fn_t) (mongoc_oidc_callback_params_t *params);
The type of the function pointer stored by mongoc_oidc_callback_t.
Parameters
+ params: A mongoc_oidc_callback_params_t object representing 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.
+ The function MUST return a mongoc_oidc_credential_t object to indi-
cate 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 is ignored if the return value is
not NULL.
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;
Represents the in/out parameters of a mongoc_oidc_callback_t.
The parameters will be passed to the mongoc_oidc_callback_fn_t stored
in an mongoc_oidc_callback_t object when it is invoked by an
mongoc_client_t or mongoc_client_pool_t object.
Parameters
The list of currently supported parameters are:
+--------------------+----------+---------------------+
|Parameter | Versions | Description |
+--------------------+----------+---------------------+
|version | 1 | The current OIDC |
| | | callback API ver- |
| | | sion number. |
+--------------------+----------+---------------------+
|user_data | 1 | A pointer to data |
| | | provided by the |
| | | user. |
+--------------------+----------+---------------------+
|timeout | 1 | The timestamp after |
| | | which the callback |
| | | function must re- |
| | | port a timeout. |
+--------------------+----------+---------------------+
|username | 1 | The username speci- |
| | | fied by the URI of |
| | | the associated |
| | | client object. |
+--------------------+----------+---------------------+
|cancel_with_timeout | 1 | An out parameter |
| | | indicating cancel- |
| | | lation of the call- |
| | | back function due |
| | | to a timeout in- |
| | | stead of an error. |
+--------------------+----------+---------------------+
The "Version" column indicates the OIDC callback API versions for which
the parameter is applicable.
Version
The version parameter is used to communicate backward compatible
changes to the OIDC callback API (i.e. the addition of a new parame-
ter).
This parameter may be used to detect when existing usage of
mongoc_oidc_callback_t or a relevant callback function may need to be
reviewed.
For example, users may add the following check to their callback func-
tion:
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 may be used to pass additional arguments to the
callback function or to return additional values out of the callback
function.
This parameter must be set in advance via
mongoc_oidc_callback_set_user_data() before the mongoc_oidc_callback_t
object is associated with a mongoc_client_t or mongoc_client_pool_t ob-
ject.
WARNING:
The lifetime of the object pointed to by user_data is managed the
user, not by mongoc_oidc_callback_t!
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);
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 used to determine when the callback function
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
from which the callback function is invoked.
Cancel With Timeout
The cancel_with_timeout out parameter indicates cancellation of the
callback function due to a timeout instead of an error.
IMPORTANT:
The callback function MUST return NULL, otherwise the invocation
will be interpreted as a success even when cancel_with_timeout is
set.
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
A NULL return value (without setting cancel_with_timeout) indicates
failure to provide an access token due to an error.
IMPORTANT:
The callback function MUST return NULL, otherwise the invocation
will be interpreted as a success.
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 represents a user-defined callback function
mongoc_oidc_callback_fn_t that returns an OIDC access token.
The callback may be used to integrate with OIDC providers that are not
supported by the built-in provider integrations (Authentication Mecha-
nism Properties).
Lifecycle
The function and optional user data stored by mongoc_oidc_callback_t
must outlive any associated client or client pool object which may in-
voke the stored callback function.
Thread Safety
The callback function stored by a mongoc_oidc_callback_t object will be
invoked by at most one thread at a time for an associated
mongoc_client_t or mongoc_client_pool_t object:
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);
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);
mongoc_client_pool_set_oidc_callback (pool, callback);
mongoc_oidc_callback_destroy (callback);
}
// ... client pool operations ...
mongoc_client_pool_destroy (pool);
}
If the callback is associated with more than one mongoc_client_t object
(in multiple threads), or with more than one mongoc_client_pool_t ob-
ject (even in a single thread), the callback function MUST support in-
vocation by more than one thread at a time:
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);
mongoc_client_set_oidc_callback (client_a, callback);
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);
mongoc_client_pool_set_oidc_callback (pool_a, callback);
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;
Represents the return value of a mongoc_oidc_callback_fn_t.
The value will be returned by the mongoc_oidc_callback_fn_t stored in
an mongoc_oidc_callback_t object when it is invoked by an associated
mongoc_client_t or mongoc_client_pool_t object.
Return Values
The list of currently supported return values are:
+-------------+----------+---------------------+
|Value | Versions | Description |
+-------------+----------+---------------------+
|access_token | 1 | The OIDC access to- |
| | | ken. |
+-------------+----------+---------------------+
|expires_in | 1 | An optional expira- |
| | | tion 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.
Expiry Duration
An optional expiry duration (in milliseconds) for the access token.
IMPORTANT:
An unset value is interpreted as an infinite expiry duration.
SEE ALSO:
+ mongoc_oidc_callback_t
+ mongoc_oidc_callback_fn_t
mongoc_optional_t
A struct to store optional boolean values.
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 ex-
plicitly set.
mongoc_query_flags_t
Flags for query operations
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. They may be bit-
wise 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_CUR- | Cursor will not be closed |
|SOR | when the last data is re- |
| | trieved. You can resume |
| | this cursor later. |
+---------------------------+----------------------------+
|MONGOC_QUERY_SECONDARY_OK | Allow query of replica set |
| | secondaries. |
+---------------------------+----------------------------+
|MONGOC_QUERY_OPLOG_REPLAY | Used internally by Mon- |
| | goDB. |
+---------------------------+----------------------------+
|MONGOC_QUERY_NO_CUR- | The server normally times |
|SOR_TIMEOUT | out an idle cursor after |
| | an inactivity period (10 |
| | minutes). This prevents |
| | that. |
+---------------------------+----------------------------+
|MONGOC_QUERY_AWAIT_DATA | Use with MON- |
| | GOC_QUERY_TAILABLE_CURSOR. |
| | Block rather than return- |
| | ing no data. After a pe- |
| | riod, time out. |
+---------------------------+----------------------------+
|MONGOC_QUERY_EXHAUST | Unused. |
+---------------------------+----------------------------+
|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, double 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 spec-
ify 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 than NULL.
Read Concern Levels
+--------------------+---------------------+---------------------+
|Macro | Description | First MongoDB ver- |
| | | sion |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "local", the | 3.2 |
|CERN_LEVEL_LOCAL | default. | |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "majority". | 3.2 |
|CERN_LEVEL_MAJORITY | | |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "lineariz- | 3.4 |
|CERN_LEVEL_LIN- | able". | |
|EARIZABLE | | |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "available". | 3.6 |
|CERN_LEVEL_AVAIL- | | |
|ABLE | | |
+--------------------+---------------------+---------------------+
|MONGOC_READ_CON- | Level "snapshot". | 4.0 |
|CERN_LEVEL_SNAPSHOT | | |
+--------------------+---------------------+---------------------+
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.
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 MON-
GOC_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 con-
nection read preferences. It allows for hinting to the driver which
nodes in a replica set should be accessed first and how.
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.
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 opera- |
| | tions read from the cur- |
| | rent replica set primary. |
+---------------------------+----------------------------+
|MONGOC_READ_SECONDARY | All operations read from |
| | among the nearest sec- |
| | ondary members of the |
| | replica set. |
+---------------------------+----------------------------+
|MONGOC_READ_PRIMARY_PRE- | In most situations, opera- |
|FERRED | tions read from the pri- |
| | mary but if it is unavail- |
| | able, operations read from |
| | secondary members. |
+---------------------------+----------------------------+
|MONGOC_READ_SECONDARY_PRE- | In most situations, opera- |
|FERRED | tions 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 con-
cerns so that your application can target operations to specific mem-
bers.
Custom read preferences and write concerns evaluate tags sets in dif-
ferent ways: read preferences consider the value of a tag when select-
ing a member to read from, while 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.
However, the nearest read mode, when combined with a tag set, will se-
lect 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, using multiple readPreferenceTags, e.g.
readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=
Note the empty value for the last one, which means "match any secondary
as a last resort".
Order matters when using multiple readPreferenceTags.
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 prefer-
ence 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 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.
Otherwise, it must be a positive integer at least MONGOC_SMALL-
EST_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.
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.
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 dis-
abled 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
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 bit-
wise 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_RE- Only remove the first
MOVE matching document from the
selector.
+-------------------------+----------------------------+
| | |
mongoc_serve|_api_t | |
A versio|ed API to use for connect|ons. |
| | |
Synopsis | | |
Used to| specify which version o| the MongoDB server's API to|use for
driver c|nnections. | |
| | |
The serv|r API type takes a mongoc|server_api_version_t. It can|option-
ally be|strict about the list of |llowed commands in that API |ersion,
and can |lso optionally provide er|ors for deprecated commands |n that
API vers|on. | |
| | |
A mongo|_server_api_t can be set |n a client, and will then be|sent to
MongoDB |or most commands run usin| that client. |
| | |
mongoc_serve|_api_version_t | |
A repres|ntation of server API ver|ion numbers. |
| | |
Synopsis | | |
Used to |pecify which version of t|e MongoDB server's API to |se for
driver c|nnections. | |
| | |
Supported AP| Versions | |
The driv|r currently supports the |ollowing MongoDB API version|:
| | |
| +---------------------+------------------------+ |
| |Enum value | MongoDB version string | |
| +---------------------+------------------------+ |
| |MONGOC_SERVER_API_V1 | "1" | |
| +---------------------+------------------------+ |
| | |
mongoc_serve|_description_t | |
Server d|scription | |
| | |
Synopsis | | |
#incl|de <mongoc/mongoc.h> | |
typed|f struct _mongoc_server_d|scription_t mongoc_server_de|cription_t
| | |
mongoc_s|rver_description_t holds|information about a mongod o| mongos
the driv|r is connected to. | |
| | |
Lifecycle | | |
Clean | up a mo|goc_server_description_t | with
mongoc_s|rver_description_destroy(| when necessary. |
| | |
Applicat|ons receive a temporary |eference to a mongoc_server_|escrip-
tion_t a| a parameter to an SDAM M|nitoring callback that must |not be
destroye|. See Introduction to App|ication Performance Monitori|g.
| | |
SEE ALSO| | |
mongo|_client_get_server_descri|tions(). |
| | |
| | |
mongoc_sessi|n_opt_t | |
#incl|de <mongoc/mongoc.h> | |
| | |
typed|f struct _mongoc_session_|pt_t mongoc_session_opt_t; |
| | |
Synopsis | | |
Start a |ession with mongoc_client|start_session(), use the ses|ion for
a sequen|e of operations and multi|document transactions, then |ree it
with |ongoc_client_session_dest|oy(). Any mongoc_curso|_t or
mongoc_c|ange_stream_t using a ses|ion must be destroyed bef|re the
session,| and a session must be de|troyed before the mongoc_cli|nt_t it
came fro|. | |
| | |
By defau|t, sessions are causally |onsistent. To disable causal|consis-
tency, |efore starting a sessi|n create a mongoc_session_op|_t with
mongoc_s|ssion_opts_new() | and | call
mongoc_s|ssion_opts_set_causal_con|istency(), then free the str|ct with
mongoc_s|ssion_opts_destroy(). | |
| | |
Unacknow|edged writes are prohibit|d 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 ses-
sion 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 sup-
port TLS protocols, which supersede SSL.
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 Mon-
goDB 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 mon-
goc_stream_t.
The API for the stream abstraction is currently private and non-exten-
sible.
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_de-
scription_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 trans-
action 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 <stdio.h>
#include <mongoc/mongoc.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) {
MONGOC_ERROR ("failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
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 {
MONGOC_ERROR ("Failed to create collection: %s", 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) {
MONGOC_ERROR ("Failed to start session: %s", 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)) {
MONGOC_ERROR ("Could not add session to opts: %s", error.message);
goto done;
}
retry_transaction:
r = mongoc_client_session_start_transaction (session, txn_opts, &error);
if (!r) {
MONGOC_ERROR ("Failed to start transaction: %s", 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) {
MONGOC_ERROR ("Insert failed: %s", 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 {
MONGOC_ERROR ("Warning: commit failed: %s", 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
Constants for transaction states
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
These constants describe the current transaction state of a session.
Flag Values
+---------------------------+----------------------------+
|MONGOC_TRANSACTION_NONE | There is no transaction in |
| | progress. |
+---------------------------+----------------------------+
|MONGOC_TRANSACTION_START- | A transaction has been |
|ING | started, but no operation |
| | has been sent to the |
| | server. |
+---------------------------+----------------------------+
|MONGOC_TRANSAC- | A transaction is in |
|TION_IN_PROGRESS | progress. |
+---------------------------+----------------------------+
|MONGOC_TRANSACTION_COMMIT- | The transaction was com- |
|TED | mitted. |
+---------------------------+----------------------------+
|MONGOC_TRANSACTION_ABORTED | The transaction was |
| | aborted. |
+---------------------------+----------------------------+
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 bit-
wise or'd together. The allow for modifying the way an update is per-
formed 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 per- |
| | forming 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 au-
thorization information.
See Connection String URI Reference on the MongoDB website for more in-
formation.
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 "mon-
godb+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.
3. The only required part of the uri. This specifies either a host-
name, IPv4 address, IPv6 address enclosed in "[" and "]", 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 'ad-
min' database.
7. Connection specific options.
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.
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.
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 follow-
ing mongod hosts:
+ db1.example.com on port 27017
+ db2.example.com on port 2500
You would use a connection string that resembles the following.
mongodb://db1.example.com,db2.example.com:2500/?replicaSet=test
SRV Example
If you have configured an SRV record with a name like "_mon-
godb._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 per-
forms a DNS SRV query to resolve the service name to one or more host-
names. 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.
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.
Set the environment variable MONGOC_EXPERIMENTAL_SRV_PREFER_TCP to pre-
fer 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 en-
vironment variable is currently experimental and subject to change.
IPv4 and IPv6
If connecting to a hostname that has both IPv4 and IPv6 DNS records,
the behavior follows RFC-6555. A connection to the IPv6 address is at-
tempted first. If IPv6 fails, then a connection is attempted to the
IPv4 address. If the connection attempt to IPv6 does not complete
within 250ms, then IPv4 is tried in parallel. Whichever succeeds con-
nection 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 configura-
tion. That is, only create an A record if the mongod is only listening
on IPv4.
Connection Options
+-------------------+------------------+------------------+-------------------------------------+
|Constant | Key | Default | Description |
+-------------------+------------------+------------------+-------------------------------------+
|MON- | retryreads | true | If "true" and |
|GOC_URI_RETRYREADS | | | 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_RETRY- | retrywrites | true if driver | If "true" and |
|WRITES | | built w/ TLS | 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 docu- |
| | | | ments, or |
| | | | deletes of sin- |
| | | | gle documents |
| | | | are retried. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_APPNAME | appname | Empty (no app- | The client ap- |
| | | name) | plication name. |
| | | | This value is |
| | | | used by MongoDB |
| | | | when it logs |
| | | | connection in- |
| | | | formation and |
| | | | profile informa- |
| | | | tion, such as |
| | | | slow queries. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_TLS | tls | Empty (not set, | {true|false}, |
| | | same as false) | indicating if |
| | | | TLS must be |
| | | | used. (See also |
| | | | mongoc_client_set_ssl_opts() |
| | | | and |
| | | | mongoc_client_pool_set_ssl_opts().) |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_COM- | compressors | Empty (no com- | Comma separated list of compres- |
|PRESSORS | | pressors) | sors, 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_CON- | connecttimeoutms | 10,000 ms (10 | This setting applies to new server |
|NECTTIMEOUTMS | | seconds) | connections. It is also used as the |
| | | | socket timeout for server discovery |
| | | | and monitoring operations. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_SOCKET- | sockettimeoutms | 300,000 ms (5 | The time in milliseconds to attempt |
|TIMEOUTMS | | minutes) | to send or receive on a socket be- |
| | | | fore the attempt times out. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_REPLI- | replicaset | Empty (no repli- | The name of the Replica Set that |
|CASET | | caset) | the driver should connect to. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_ZLIB- | zlibcompression- | -1 | When the MONGOC_URI_COMPRESSORS in- |
|COMPRESSIONLEVEL | level | | cludes "zlib" this options config- |
| | | | ures the zlib compression level, |
| | | | when the zlib compressor is used to |
| | | | compress client data. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_LOAD- | loadbalanced | false | If true, this indicates the driver |
|BALANCED | | | is connecting to a MongoDB cluster |
| | | | behind a load balancer. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_SRVMAX- | srvmaxhosts | 0 | If zero, the number of hosts in DNS |
|HOSTS | | | results is unlimited. If greater |
| | | | than zero, the number of hosts in |
| | | | DNS results is limited to being |
| | | | less than or equal to the given |
| | | | value. |
+-------------------+------------------+------------------+-------------------------------------+
WARNING:
Setting any of the *timeoutMS options above to either 0 or a nega-
tive value is discouraged due to unspecified and inconsistent behav-
ior. The "default value" historically specified as a fallback for 0
or a negative value is NOT related to the default values for the
*timeoutMS options documented above. The meaning of a timeout of 0
or a negative value may vary depending on the operation being exe-
cuted, even when specified by the same URI option. To specify the
documented default value for a *timeoutMS option, use the MONGOC_DE-
FAULT_* constants defined in mongoc-client.h instead.
Authentication Options
+--------------------+--------------------+--------------------------+
|Constant | Key | Description |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_AUTH- | authmechanism | Specifies the mech- |
|MECHANISM | | anism to use when |
| | | authenticating as |
| | | the provided user. |
| | | See Authentication |
| | | for supported val- |
| | | ues. |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_AUTH- | authmechanismprop- | Additional proper- |
|MECHANISMPROPERTIES | erties | ties for the speci- |
| | | fied mechanism us- |
| | | ing key-value pair |
| | | format, e.g. |
| | | key1:value1,key2:value2. |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_AUTH- | authsource | The name of the database |
|SOURCE | | to which authentication |
| | | commands are sent or |
| | | $external depending on |
| | | the specified mechanism. |
| | | Overrides the auth data- |
| | | base in the URI when ap- |
| | | plicable. |
+--------------------+--------------------+--------------------------+
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
+---------------+----------------------------+
|Key | Value |
+---------------+----------------------------+
|ENVIRONMENT | The name of a built-in |
| | OIDC provider integration. |
| | Must be one of ["azure", |
| | "gcp", "k8s"]. |
+---------------+----------------------------+
|TOKEN_RESOURCE | The URI of the target re- |
| | source. 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
+-----------------------+----------------------------+
|Key | Value |
+-----------------------+----------------------------+
|SERVICE_NAME | Optional. Defaults to |
| | "mongodb". |
+-----------------------+----------------------------+
|CANONICALIZE_HOST_NAME | Optional. Must be one of |
| | ["false", "true"]. "false" |
| | performs no canonicaliza- |
| | tion (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 authenti- |
| | cation 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
+------------------+----------------------------+
|Key | Value |
+------------------+----------------------------+
|AWS_SESSION_TOKEN | Optional. An AWS session |
| | token to use for authenti- |
| | cation with temporary cre- |
| | dentials. |
+------------------+----------------------------+
Deprecated Mechanism Property Options
The following options have been deprecated and may be removed from fu-
ture releases of libmongoc.
+----------------+----------------+------------------+----------------+
|Constant | Key | Deprecated For | Key |
+----------------+----------------+------------------+----------------+
|MON- | canonicalize- | MONGOC_URI_AUTH- | authmechanism- |
|GOC_URI_CANONI- | hostname | MECHANISMPROPER- | properties |
|CALIZEHOSTNAME | | TIES (CANONICAL- | |
| | | IZE_HOST_NAME) | |
+----------------+----------------+------------------+----------------+
|MONGOC_URI_GSS- | gssapiservice- | MONGOC_URI_AUTH- | authmechanism- |
|APISERVICENAME | name | MECHANISMPROPER- | properties |
| | | TIES (SER- | |
| | | VICE_NAME) | |
+----------------+----------------+------------------+----------------+
TLS Options
+--------------------+---------------------+---------------------+
|Constant | Key | Description |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLS | tls | {true|false}, indi- |
| | | cating if TLS must |
| | | be used. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSCER- | tlscertificatekey- | Path to PEM format- |
|TIFICATEKEYFILE | file | ted Private Key, |
| | | with its Public |
| | | Certificate con- |
| | | catenated at the |
| | | end. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSCER- | tlscertificatekey- | The password, if |
|TIFICATEKEY- | password | any, to use to un- |
|FILEPASSWORD | | lock encrypted Pri- |
| | | vate Key. |
+--------------------+---------------------+---------------------+
|MON- | tlscafile | One, or a bundle |
|GOC_URI_TLSCAFILE | | of, Certificate Au- |
| | | thorities whom |
| | | should be consid- |
| | | ered to be trusted. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSAL- | tlsallowinvalidcer- | Accept and ignore |
|LOWINVALIDCERTIFI- | tificates | certificate verifi- |
|CATES | | cation errors (e.g. |
| | | untrusted issuer, |
| | | expired, etc.) |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSAL- | tlsallowinvalid- | Ignore hostname |
|LOWINVALIDHOSTNAMES | hostnames | verification of the |
| | | certificate (e.g. |
| | | Man In The Middle, |
| | | using valid cer- |
| | | tificate, but is- |
| | | sued for another |
| | | hostname) |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSINSE- | tlsinsecure | {true|false}, indi- |
|CURE | | cating if insecure |
| | | TLS options should |
| | | be used. Currently |
| | | this implies MON- |
| | | GOC_URI_TLSALLOWIN- |
| | | VALIDCERTIFICATES |
| | | and MONGOC_URI_TL- |
| | | SALLOWINVALIDHOST- |
| | | NAMES. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSDIS- | tlsdisablecertifi- | {true|false}, indi- |
|ABLECERTIFICATERE- | caterevocationcheck | cates if revocation |
|VOCATIONCHECK | | checking (CRL / |
| | | OCSP) should be |
| | | disabled. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSDIS- | tlsdisableocspend- | {true|false}, indi- |
|ABLEOCSPEND- | pointcheck | cates if OCSP re- |
|POINTCHECK | | sponder endpoints |
| | | should not be re- |
| | | quested 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 fu-
ture releases of libmongoc.
+----------------------+------------------+-------------------+------------------+
|Constant | Key | Deprecated For | Key |
+----------------------+------------------+-------------------+------------------+
|MONGOC_URI_SSL | ssl | MONGOC_URI_TLS | tls |
+----------------------+------------------+-------------------+------------------+
|MON- | sslclientcer- | MON- | tlscertifi- |
|GOC_URI_SSLCLIENTCER- | tificatekeyfile | GOC_URI_TLSCER- | catekeyfile |
|TIFICATEKEYFILE | | TIFICATEKEYFILE | |
+----------------------+------------------+-------------------+------------------+
|MON- | sslclientcer- | MON- | tlscertifi- |
|GOC_URI_SSLCLIENTCER- | tificatekeypass- | GOC_URI_TLSCER- | catekeypassword |
|TIFICATEKEYPASSWORD | word | TIFICATEKEY- | |
| | | FILEPASSWORD | |
+----------------------+------------------+-------------------+------------------+
|MONGOC_URI_SSLCER- | sslcertifi- | MON- | tlscafile |
|TIFICATEAUTHORITYFILE | cateauthority- | GOC_URI_TLSCAFILE | |
| | file | | |
+----------------------+------------------+-------------------+------------------+
|MONGOC_URI_SSLALLOW- | sslallowinvalid- | MONGOC_URI_TLSAL- | tlsallowinvalid- |
|INVALIDCERTIFICATES | certificates | LOWINVALIDCER- | certificates |
| | | TIFICATES | |
+----------------------+------------------+-------------------+------------------+
|MONGOC_URI_SSLALLOW- | sslallowinvalid- | MONGOC_URI_TLSAL- | tlsallowinvalid- |
|INVALIDHOSTNAMES | hostnames | LOWINVALIDHOST- | hostnames |
| | | NAMES | |
+----------------------+------------------+-------------------+------------------+
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 (de-
fault 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 in-
sert--the thread rescans all servers every half-second. In this situa-
tion 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 sin-
gle-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 try-
ing to find it, then succeeds or returns an error with domain MON-
GOC_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 serverSelec-
tionTryOnce is set "false".
+--------------------+---------------------+---------------------+
|Constant | Key | Description |
+--------------------+---------------------+---------------------+
|MONGOC_URI_HEART- | heartbeatfrequen- | The interval be- |
|BEATFREQUENCYMS | cyms | tween server moni- |
| | | toring checks. De- |
| | | faults to 10,000ms |
| | | (10 seconds) in |
| | | pooled |
| | | (multi-threaded) |
| | | mode, 60,000ms (60 |
| | | seconds) in |
| | | non-pooled mode |
| | | (single-threaded). |
+--------------------+---------------------+---------------------+
|MONGOC_URI_SERVERS- | serverselection- | A timeout in mil- |
|ELECTIONTIMEOUTMS | timeoutms | liseconds to block |
| | | for server selec- |
| | | tion before throw- |
| | | ing an exception. |
| | | The default is |
| | | 30,0000ms (30 sec- |
| | | onds). |
+--------------------+---------------------+---------------------+
|MONGOC_URI_SERVERS- | serverselectiontry- | If "true", the |
|ELECTIONTRYONCE | once | 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 serverSelec- |
| | | tionTimeoutMS mil- |
| | | liseconds (pausing |
| | | a half second be- |
| | | tween attempts). |
| | | The default for |
| | | serverSelectionTry- |
| | | Once is "false" for |
| | | pooled clients, |
| | | otherwise "true". |
| | | Pooled clients ig- |
| | | nore serverSelec- |
| | | tionTryOnce; they |
| | | signal the thread |
| | | to rescan the |
| | | topology every |
| | | half-second until |
| | | serverSelection- |
| | | TimeoutMS expires. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_SOCK- | socketcheckinter- | Only applies to |
|ETCHECKINTERVALMS | valms | single threaded |
| | | clients. If a |
| | | socket has not been |
| | | used within this |
| | | time, its connec- |
| | | tion is checked |
| | | with a quick |
| | | "hello" call before |
| | | it is used again. |
| | | Defaults to 5,000ms |
| | | (5 seconds). |
+--------------------+---------------------+---------------------+
|MONGOC_URI_DIRECT- | directconnection | If "true", the |
|CONNECTION | | driver connects to |
| | | a single server di- |
| | | rectly and will not |
| | | monitor additional |
| | | servers. If |
| | | "false", the driver |
| | | connects based on |
| | | the presence and |
| | | value of the repli- |
| | | caSet option. |
+--------------------+---------------------+---------------------+
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.
+--------------------+--------------------+--------------------------+
|Constant | Key | Description |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_MAXPOOL- | maxpoolsize | The maximum number |
|SIZE | | 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 an- |
| | | other thread pushes |
| | | a client. |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_WAIT- | waitqueuetimeoutms | The maximum time to wait |
|QUEUETIMEOUTMS | | for a client to become |
| | | available from the pool. |
+--------------------+--------------------+--------------------------+
Write Concern Options
+-------------------+------------+---------------------+
|Constant | Key | Description |
+-------------------+------------+---------------------+
MONGOC_URI_W w Determines the
write concern
(guarantee). Valid
values:
+ 0 = The
driver
will not
acknowl-
edge write
operations
but will
pass or
handle any
network
and socket
errors
that it
receives
to the
client. If
you dis-
able write
concern
but enable
the get-
LastError
command's
w option,
w over-
rides the
w option.
+ 1 = Pro-
vides ba-
sic ac-
knowledge-
ment of
write op-
erations.
By speci-
fying 1,
you re-
quire that
a stand-
alone mon-
god in-
stance, or
the pri-
mary for
replica
sets, ac-
knowledge
all write
opera-
tions. For
drivers
released
after the
default
write con-
cern
change,
this is
the de-
fault
write con-
cern set-
ting.
+ majority =
For
replica
sets, if
you spec-
ify the
special
majority
value to w
option,
write op-
erations
will only
return
success-
fully af-
ter a ma-
jority of
the con-
figured
replica
set mem-
bers have
acknowl-
edged the
write op-
eration.
+ n = For
replica
sets, if
you spec-
ify a num-
ber n
greater
than 1,
operations
with this
write con-
cern re-
turn only
after n
members of
the set
have ac-
knowledged
the write.
If you set
n to a
number
that is
greater
than the
number of
available
set mem-
bers or
members
that hold
data, Mon-
goDB will
wait, po-
tentially
indefi-
nitely,
for these
members to
become
available.
+ tags = For
replica
sets, you
can spec-
ify a tag
set to re-
quire that
all mem-
bers of
the set
that have
these tags
configured
return
confirma-
tion of
the write
operation.
+-------------------+------------+---------------------+
|MONGOC_URI_WTIME- | wtimeoutms | The time in mil- |
|OUTMS | | liseconds to wait |
| | | for replication to |
| | | succeed, as speci- |
| | | fied in the w op- |
| | | tion, before timing |
| | | out. When wtime- |
| | | outMS is 0, write |
| | | operations will |
| | | never time out. |
+-------------------+------------+---------------------+
|MONGOC_URI_JOURNAL | journal | Controls whether |
| | | write operations |
| | | will wait until the |
| | | mongod acknowledges |
| | | the write opera- |
| | | tions and commits |
| | | the data to the on |
| | | disk journal. |
| | | |
| | | + true = |
| | | Enables |
| | | journal |
| | | commit ac- |
| | | knowledge- |
| | | ment write |
| | | concern. |
| | | Equivalent |
| | | to speci- |
| | | fying the |
| | | getLastEr- |
| | | ror com- |
| | | mand with |
| | | the j op- |
| | | tion en- |
| | | abled. |
| | | |
| | | + false = |
| | | Does not |
| | | require |
| | | that mon- |
| | | god commit |
| | | write op- |
| | | erations |
| | | to the |
| | | journal |
| | | before ac- |
| | | knowledg- |
| | | ing the |
| | | write op- |
| | | eration. |
| | | This is |
| | | the de- |
| | | fault op- |
| | | tion for |
| | | the jour- |
| | | nal param- |
| | | eter. |
+-------------------+------------+---------------------+
Read Concern Options
+--------------------+------------------+---------------------+
|Constant | Key | Description |
+--------------------+------------------+---------------------+
|MONGOC_URI_READCON- | readconcernlevel | The level of isola- |
|CERNLEVEL | | tion for read oper- |
| | | ations. If the |
| | | level is left un- |
| | | specified, 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.
+--------------------+---------------------+---------------------+
|Constant | Key | Description |
+--------------------+---------------------+---------------------+
|MONGOC_URI_READ- | readpreference | Specifies the |
|PREFERENCE | | replica set read |
| | | preference for this |
| | | connection. This |
| | | setting overrides |
| | | any secondaryOk |
| | | value. The read |
| | | preference values |
| | | are the following: |
| | | |
| | | + primary |
| | | (default) |
| | | |
| | | + prima- |
| | | ryPre- |
| | | ferred |
| | | |
| | | + secondary |
| | | |
| | | + sec- |
| | | ondaryPre- |
| | | ferred |
| | | |
| | | + nearest |
+--------------------+---------------------+---------------------+
|MONGOC_URI_READ- | readpreferencetags | A representation of |
|PREFERENCETAGS | | a tag set. See also |
| | | Tag Sets. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_LO- | localthresholdms | How far to distrib- |
|CALTHRESHOLDMS | | ute queries, beyond |
| | | the server with the |
| | | fastest round-trip |
| | | time. By default, |
| | | only servers within |
| | | 15ms of the fastest |
| | | round-trip time re- |
| | | ceive queries. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_MAXSTAL- | maxstalenessseconds | The maximum repli- |
|ENESSSECONDS | | cation lag, in wall |
| | | clock time, that a |
| | | secondary can suf- |
| | | fer and still be |
| | | eligible. The |
| | | smallest allowed |
| | | value for maxStale- |
| | | nessSeconds is 90 |
| | | seconds. |
+--------------------+---------------------+---------------------+
NOTE:
When connecting to more than one mongos, libmongoc's localThresh-
oldMS 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.
Legacy Options
For historical reasons, the following options are available. They
should however not be used.
+----------------+------+---------------------+
|Constant | Key | Description |
+----------------+------+---------------------+
|MONGOC_URI_SAFE | safe | {true|false} Same |
| | | as w={1|0} |
+----------------+------+---------------------+
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/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.
#if MONGOC_CHECK_VERSION(1, 1, 0)
static void
do_something (void)
{
}
#endif
mongoc_write_concern_t
Write Concern abstraction
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.
You can specify a write concern on connection objects, database ob-
jects, 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 collec-
tion's write concern, and a write concern error or timeout in the re-
sponse is considered a failure.
Exceptions to this principle are the generic command functions:
+ mongoc_client_command_simple()
+ mongoc_database_command_simple()
+ mongoc_collection_command_simple()
These generic command functions do not automatically apply a write con-
cern, and they do not check the server response for a write concern er-
ror 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_DE- | By default, writes block |
|FAULT (1) | awaiting acknowledgement |
| | from MongoDB. Acknowledged |
| | write concern allows |
| | clients to catch network, |
| | duplicate key, and other |
| | errors. |
+---------------------------+----------------------------+
|MONGOC_WRITE_CONCERN_W_UN- | With this write concern, |
|ACKNOWLEDGED (0) | MongoDB does not acknowl- |
| | edge the receipt of write |
| | operation. Unacknowledged |
| | is similar to errors ig- |
| | nored; however, mongoc at- |
| | tempts to receive and han- |
| | dle network errors when |
| | possible. |
+---------------------------+----------------------------+
|MONGOC_WRITE_CONCERN_W_MA- | Block until a write has |
|JORITY (majority) | been propagated to a ma- |
| | jority of the nodes in the |
| | replica set. |
+---------------------------+----------------------------+
|n | Block until a write has |
| | been propagated to at |
| | least n nodes in the |
| | replica set. |
+---------------------------+----------------------------+
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:
+ Command Logging and Monitoring: events related to all application op-
erations.
+ SDAM Monitoring: events related to the driver's Server Discovery And
Monitoring logic.
To receive notifications, create a mongoc_apm_callbacks_t with
mongoc_apm_callbacks_new(), set callbacks on it, then pass it to
mongoc_client_set_apm_callbacks() or
mongoc_client_pool_set_apm_callbacks().
Command-Monitoring Example
example-command-monitoring.c
/* 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: %s\n"
"error message: %s\n",
uri_string,
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;
}
This example program prints:
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
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.
The final "insert" command is considered successful, despite the
writeError, because the server replied to the overall command with
"ok": 1.
SDAM Monitoring Example
example-sdam-monitoring.c
/* 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);
}
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);
}
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");
}
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);
}
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: %s\n"
"error message: %s\n",
uri_string,
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;
}
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 discov-
ers the third member, "localhost:27019", and adds it to the topology.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_REFERENCE(3)
mongoc_remove_flags_t.3
MONGOC_REMOVE_FLAGS_T(3) libmongoc MONGOC_REMOVE_FLAGS_T(3)
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 bit-
wise 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_RE- | Only remove the first |
|MOVE | matching document from the |
| | selector. |
+-------------------------+----------------------------+
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_REMOVE_FLAGS_T(3)
mongoc_server_api_copy.3
MONGOC_SERVER_API_COPY(3) libmongoc MONGOC_SERVER_API_COPY(3)
SYNOPSIS
mongoc_server_api_t *
mongoc_server_api_copy (const mongoc_server_api_t *api);
Creates a deep copy of api.
PARAMETERS
+ api: A mongoc_server_api_t.
RETURNS
Returns a newly allocated copy of api that must be freed with
mongoc_server_api_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_API_COPY(3)
mongoc_server_api_deprecation_errors.3
MONGOC_SERVER_API_DEPRECATION_ERRORS(3)ongocC_SERVER_API_DEPRECATION_ERRORS(3)
SYNOPSIS
void
mongoc_server_api_deprecation_errors (mongoc_server_api_t *api,
bool deprecation_errors);
Set whether or not to error on commands that are deprecated in this API
version.
PARAMETERS
+ api: A mongoc_server_api_t.
+ deprecation_errors: Whether or not to error on commands that are dep-
recated.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_SERVER_API_DEPRECATION_ERRORS(3)
mongoc_server_api_destroy.3
MONGOC_SERVER_API_DESTROY(3) libmongoc MONGOC_SERVER_API_DESTROY(3)
SYNOPSIS
void
mongoc_server_api_destroy (mongoc_server_api_t *api);
Free a mongoc_server_api_t. Does nothing if api is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_API_DESTROY(3)
mongoc_server_api_get_deprecation_errors.3
MONGOC_SERVER_API_GET_DEPRECATION_ERRORS(3)cRVER_API_GET_DEPRECATION_ERRORS(3)
SYNOPSIS
const mongoc_optional_t *
mongoc_server_api_get_deprecation_errors (const mongoc_server_api_t *api);
Returns the value of the deprecation_errors flag for the
mongoc_server_api_t.
PARAMETERS
+ api: A mongoc_server_api_t.
RETURNS
Returns a mongoc_optional_t indicating whether the deprecation_errors
flag was set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025VER_API_GET_DEPRECATION_ERRORS(3)
mongoc_server_api_get_strict.3
MONGOC_SERVER_API_GET_STRICT(3) libmongoc MONGOC_SERVER_API_GET_STRICT(3)
SYNOPSIS
const mongoc_optional_t *
mongoc_server_api_get_strict (const mongoc_server_api_t *api);
Returns the value of the strict flag for the mongoc_server_api_t.
PARAMETERS
+ api: A mongoc_server_api_t.
RETURNS
Returns a mongoc_optional_t indicating whether the strict flag was set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_API_GET_STRICT(3)
mongoc_server_api_get_version.3
MONGOC_SERVER_API_GET_VERSION(3) libmongoc MONGOC_SERVER_API_GET_VERSION(3)
SYNOPSIS
mongoc_server_api_version_t
mongoc_server_api_get_version (const mongoc_server_api_t *api);
Fetch the declared API version as from a mongoc_server_api_t.
PARAMETERS
+ api: A mongoc_server_api_t.
RETURNS
Returns a mongoc_server_api_version_t with the API version declare in
the mongoc_server_api_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_API_GET_VERSION(3)
mongoc_server_api_new.3
MONGOC_SERVER_API_NEW(3) libmongoc MONGOC_SERVER_API_NEW(3)
SYNOPSIS
mongoc_server_api_t *
mongoc_server_api_new (mongoc_server_api_version_t version);
Create a struct to hold server API preferences.
RETURNS
A new mongoc_server_api_t you must free with
mongoc_server_api_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_API_NEW(3)
mongoc_server_api_strict.3
MONGOC_SERVER_API_STRICT(3) libmongoc MONGOC_SERVER_API_STRICT(3)
SYNOPSIS
void
mongoc_server_api_strict (mongoc_server_api_t *api, bool strict);
Set whether to be strict about the list of allowed commands in this API
version.
PARAMETERS
+ api: A mongoc_server_api_t.
+ strict: Whether or not to be struct about the list of allowed API
commands.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_API_STRICT(3)
mongoc_server_api_t.3
MONGOC_SERVER_API_T(3) libmongoc MONGOC_SERVER_API_T(3)
A versioned API to use for connections.
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 option-
ally 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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_API_T(3)
mongoc_server_api_version_from_string.3
MONGOC_SERVER_API_VERSION_FROM_STRING(3)ngoc_SERVER_API_VERSION_FROM_STRING(3)
SYNOPSIS
bool
mongoc_server_api_version_from_string (const char *version,
mongoc_server_api_version_t *out);
Given a string version, populates out with the equivalent
mongoc_server_api_version_t if version represents a valid API version.
PARAMETERS
+ version: A string representing the version identifier.
+ out: A pointer to a mongoc_server_api_version_t.
RETURNS
True on success, false on failure. On success, out is populated with
the converted version string. On failure, out is not altered.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025SERVER_API_VERSION_FROM_STRING(3)
mongoc_server_api_version_t.3
MONGOC_SERVER_API_VERSION_T(3) libmongoc MONGOC_SERVER_API_VERSION_T(3)
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:
+---------------------+------------------------+
|Enum value | MongoDB version string |
+---------------------+------------------------+
|MONGOC_SERVER_API_V1 | "1" |
+---------------------+------------------------+
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_API_VERSION_T(3)
mongoc_server_api_version_to_string.3
MONGOC_SERVER_API_VERSION_TO_STRING(3)mongocOC_SERVER_API_VERSION_TO_STRING(3)
SYNOPSIS
const char *
mongoc_server_api_version_to_string (mongoc_server_api_version_t version);
Returns the string representation of version, or NULL if version has no
string representation.
PARAMETERS
+ version: A mongoc_server_api_version_t
RETURNS
Returns the string representation of version or NULL. The returned
string should not be freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_SERVER_API_VERSION_TO_STRING(3)
mongoc_server_description_destroy.3
MONGOC_SERVER_DESCRIPTION_DESTROY(3)ibmongocNGOC_SERVER_DESCRIPTION_DESTROY(3)
SYNOPSIS
void
mongoc_server_description_destroy (mongoc_server_description_t *description);
PARAMETERS
+ description: A mongoc_server_description_t.
DESCRIPTION
Frees all resources associated with the server description. Does noth-
ing if description is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_SERVER_DESCRIPTION_DESTROY(3)
mongoc_server_description_hello_response.3
MONGOC_SERVER_DESCRIPTION_HELLO_RESPONSE(3)cRVER_DESCRIPTION_HELLO_RESPONSE(3)
SYNOPSIS
const bson_t *
mongoc_server_description_hello_response (
const mongoc_server_description_t *description);
PARAMETERS
+ description: A mongoc_server_description_t.
DESCRIPTION
The client or client pool periodically runs a "hello" command on each
server, to update its view of the MongoDB deployment. Use
mongoc_client_get_server_descriptions() and mongoc_server_descrip-
tion_hello_response() to get the most recent "hello" response.
RETURNS
A reference to a BSON document, owned by the server description. The
document is empty if the driver is not connected to the server.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025VER_DESCRIPTION_HELLO_RESPONSE(3)
mongoc_server_description_host.3
MONGOC_SERVER_DESCRIPTION_HOST(3) libmongoc MONGOC_SERVER_DESCRIPTION_HOST(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_server_description_host (const mongoc_server_description_t *description);
PARAMETERS
+ description: A mongoc_server_description_t.
DESCRIPTION
Return the server's host and port. This object is owned by the server
description.
RETURNS
Changed in version 2.0.0: The return type changed from mon-
goc_host_list_t * to const mongoc_host_list_t *.
A reference to the server description's mongoc_host_list_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_SERVER_DESCRIPTION_HOST(3)
mongoc_server_description_id.3
MONGOC_SERVER_DESCRIPTION_ID(3) libmongoc MONGOC_SERVER_DESCRIPTION_ID(3)
SYNOPSIS
uint32_t
mongoc_server_description_id (const mongoc_server_description_t *description);
PARAMETERS
+ description: A mongoc_server_description_t.
DESCRIPTION
Get the server's id, an opaque identifier generated by the client or
client pool.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_DESCRIPTION_ID(3)
mongoc_server_description_last_update_time.3
MONGOC_SERVER_DESCRIPTION_LAST_UPDATEbTIME(3)R_DESCRIPTION_LAST_UPDATE_TIME(3)
SYNOPSIS
int64_t
mongoc_server_description_last_update_time (const mongoc_server_description_t *description);
PARAMETERS
+ description: A mongoc_server_description_t.
DESCRIPTION
Get the last point in time when we processed a hello for this server,
or, if we have not processed any hellos since creating the description,
the time the server description was initialized.
RETURNS
The server's last update time, in microseconds.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,S2025R_DESCRIPTION_LAST_UPDATE_TIME(3)
mongoc_server_description_new_copy.3
MONGOC_SERVER_DESCRIPTION_NEW_COPY(3)bmongocGOC_SERVER_DESCRIPTION_NEW_COPY(3)
SYNOPSIS
mongoc_server_description_t *
mongoc_server_description_new_copy (
const mongoc_server_description_t *description);
PARAMETERS
+ description: A mongoc_server_description_t.
DESCRIPTION
Performs a deep copy of description.
RETURNS
Returns a newly allocated copy of description that should be freed with
mongoc_server_description_destroy() when no longer in use. Returns NULL
if description is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_SERVER_DESCRIPTION_NEW_COPY(3)
mongoc_server_description_round_trip_time.3
MONGOC_SERVER_DESCRIPTION_ROUND_TRIPiTIME(3)VER_DESCRIPTION_ROUND_TRIP_TIME(3)
SYNOPSIS
int64_t
mongoc_server_description_round_trip_time (
const mongoc_server_description_t *description);
PARAMETERS
+ description: A mongoc_server_description_t.
DESCRIPTION
Get the server's round trip time in milliseconds. This is the client's
measurement of the duration of a "hello" command.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025ER_DESCRIPTION_ROUND_TRIP_TIME(3)
mongoc_server_description_t.3
MONGOC_SERVER_DESCRIPTION_T(3) libmongoc MONGOC_SERVER_DESCRIPTION_T(3)
Server description
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.
Applications receive a temporary reference to a mongoc_server_descrip-
tion_t as a parameter to an SDAM Monitoring callback that must not be
destroyed. See Introduction to Application Performance Monitoring.
SEE ALSO:
mongoc_client_get_server_descriptions().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SERVER_DESCRIPTION_T(3)
mongoc_server_description_type.3
MONGOC_SERVER_DESCRIPTION_TYPE(3) libmongoc MONGOC_SERVER_DESCRIPTION_TYPE(3)
SYNOPSIS
const char *
mongoc_server_description_type (const mongoc_server_description_t *description);
PARAMETERS
+ description: A mongoc_server_description_t.
DESCRIPTION
This function returns a string, one of the server types defined in the
Server Discovery And Monitoring Spec:
+ Standalone
+ Mongos
+ PossiblePrimary
+ LoadBalancer
+ RSPrimary
+ RSSecondary
+ RSArbiter
+ RSOther
+ RSGhost
+ Unknown
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_SERVER_DESCRIPTION_TYPE(3)
mongoc_server_descriptions_destroy_all.3
MONGOC_SERVER_DESCRIPTIONS_DESTROY_ALL(3)gocSERVER_DESCRIPTIONS_DESTROY_ALL(3)
SYNOPSIS
void
mongoc_server_descriptions_destroy_all (mongoc_server_description_t **sds,
size_t n);
Frees the array of mongoc_server_description_t structs returned by
mongoc_client_get_server_descriptions().
PARAMETERS
+ sds: The array of server descriptions.
+ n: The number of elements in sds.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025ERVER_DESCRIPTIONS_DESTROY_ALL(3)
mongoc_session_opt_t.3
MONGOC_SESSION_OPT_T(3) libmongoc MONGOC_SESSION_OPT_T(3)
#include <mongoc/mongoc.h>
typedef struct _mongoc_session_opt_t mongoc_session_opt_t;
SYNOPSIS
Start a session with mongoc_client_start_session(), use the 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.
By default, sessions are causally consistent. To disable causal consis-
tency, 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 ses-
sion 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().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SESSION_OPT_T(3)
mongoc_session_opts_clone.3
MONGOC_SESSION_OPTS_CLONE(3) libmongoc MONGOC_SESSION_OPTS_CLONE(3)
SYNOPSIS
mongoc_session_opt_t *
mongoc_session_opts_clone (const mongoc_session_opt_t *opts);
Create a copy of a session options struct.
PARAMETERS
+ opts: A mongoc_session_opt_t.
RETURNS
A new mongoc_session_opt_t that must be freed with
mongoc_session_opts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SESSION_OPTS_CLONE(3)
mongoc_session_opts_destroy.3
MONGOC_SESSION_OPTS_DESTROY(3) libmongoc MONGOC_SESSION_OPTS_DESTROY(3)
SYNOPSIS
void
mongoc_session_opts_destroy (mongoc_session_opt_t *opts);
Free a mongoc_session_opt_t. Does nothing if opts is NULL.
PARAMETERS
+ opts: A mongoc_session_opt_t.
EXAMPLE
See the example code for mongoc_session_opts_set_causal_consistency().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SESSION_OPTS_DESTROY(3)
mongoc_session_opts_get_causal_consistency.3
MONGOC_SESSION_OPTS_GET_CAUSAL_CONSISTENCY(3)ON_OPTS_GET_CAUSAL_CONSISTENCY(3)
SYNOPSIS
bool
mongoc_session_opts_get_causal_consistency (const mongoc_session_opt_t *opts);
Return true if this session is configured for causal consistency (the
default), else false. See mongoc_session_opts_set_causal_consistency().
PARAMETERS
+ opts: A mongoc_session_opt_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,S2025ON_OPTS_GET_CAUSAL_CONSISTENCY(3)
mongoc_session_opts_get_default_transaction_opts.3
MONGOC_SESSION_OPTS_GET_DEFAULTOTRANSACTIONcOPTS(3)DEFAULT_TRANSACTION_OPTS(3)
SYNOPSIS
const mongoc_transaction_opt_t *
mongoc_session_opts_get_default_transaction_opts (const mongoc_session_opt_t *opts);
The default options for transactions started with this session. See
mongoc_session_opts_set_default_transaction_opts().
PARAMETERS
+ opts: A mongoc_session_opt_t.
RETURNS
A mongoc_transaction_opt_t that is valid only for the lifetime of opts.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOCMayS12,N2025S_GET_DEFAULT_TRANSACTION_OPTS(3)
mongoc_session_opts_get_snapshot.3
MONGOC_SESSION_OPTS_GET_SNAPSHOT(3)libmongocONGOC_SESSION_OPTS_GET_SNAPSHOT(3)
SYNOPSIS
bool
mongoc_session_opts_get_snapshot (const mongoc_session_opt_t *opts);
Return true if this session is configured for snapshot reads, false by
default. See mongoc_session_opts_set_snapshot().
PARAMETERS
+ opts: A mongoc_session_opt_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_SESSION_OPTS_GET_SNAPSHOT(3)
mongoc_session_opts_get_transaction_opts.3
MONGOC_SESSION_OPTS_GET_TRANSACTIONlOPTS(3)cSSION_OPTS_GET_TRANSACTION_OPTS(3)
SYNOPSIS
mongoc_transaction_opt_t *
mongoc_session_opts_get_transaction_opts (
const mongoc_client_session_t *session);
The options for the current transaction started with this session.
If this session is not in a transaction, then the returned value is
NULL. See mongoc_client_session_in_transaction().
PARAMETERS
+ session: A mongoc_client_session_t.
RETURNS
If the session is in a transaction, a new mongoc_transaction_opt_t that
must be freed with mongoc_transaction_opts_destroy(). Otherwise, NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025SION_OPTS_GET_TRANSACTION_OPTS(3)
mongoc_session_opts_new.3
MONGOC_SESSION_OPTS_NEW(3) libmongoc MONGOC_SESSION_OPTS_NEW(3)
SYNOPSIS
mongoc_session_opt_t *
mongoc_session_opts_new (void);
Start a session with mongoc_client_start_session(), use the 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.
By default, sessions are causally consistent. To disable causal consis-
tency, 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 ses-
sion 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().
RETURNS
A new mongoc_session_opt_t that must be freed with
mongoc_session_opts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SESSION_OPTS_NEW(3)
mongoc_session_opts_set_causal_consistency.3
MONGOC_SESSION_OPTS_SET_CAUSAL_CONSISTENCY(3)ON_OPTS_SET_CAUSAL_CONSISTENCY(3)
SYNOPSIS
void
mongoc_session_opts_set_causal_consistency (mongoc_session_opt_t *opts,
bool causal_consistency);
Configure causal consistency in a session. If true (the default), each
operation in the session will be causally ordered after the previous
read or write operation. Set to false to disable causal consistency.
See the MongoDB Manual Entry for Causal Consistency.
Causal consistency and snapshot reads are mutually exclusive. Attempt-
ing to set both to true will result in an error. See
mongoc_session_opts_set_snapshot().
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 par-
ticipate in causal consistency.
PARAMETERS
+ opts: A mongoc_session_opt_t.
+ causal_consistency: True or false.
EXAMPLE
mongoc_client_t *client;
mongoc_session_opt_t *session_opts;
mongoc_client_session_t *client_session;
mongoc_collection_t *collection;
bson_t insert_opts = BSON_INITIALIZER;
bson_t *doc;
bson_error_t error;
bool r;
client = mongoc_client_new ("mongodb://example/?appname=session-opts-example");
mongoc_client_set_error_api (client, 2);
session_opts = mongoc_session_opts_new ();
mongoc_session_opts_set_causal_consistency (session_opts, false);
client_session = mongoc_client_start_session (client, session_opts, &error);
mongoc_session_opts_destroy (session_opts);
if (!client_session) {
fprintf (stderr, "Failed to start session: %s\n", error.message);
abort ();
}
collection = mongoc_client_get_collection (client, "test", "collection");
doc = BCON_NEW ("_id", BCON_INT32 (1));
r = mongoc_client_session_append (client_session, &insert_opts, NULL);
if (!r) {
fprintf (stderr, "mongoc_client_session_append failed: %s\n", error.message);
abort ();
}
r = mongoc_collection_insert_one (
collection, doc, &insert_opts, NULL /* reply */, &error);
if (!r) {
fprintf (stderr, "Insert failed: %s\n", error.message);
abort ();
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayG12,S2025ON_OPTS_SET_CAUSAL_CONSISTENCY(3)
mongoc_session_opts_set_default_transaction_opts.3
MONGOC_SESSION_OPTS_SET_DEFAULTOTRANSACTIONcOPTS(3)DEFAULT_TRANSACTION_OPTS(3)
SYNOPSIS
void
mongoc_session_opts_set_default_transaction_opts (
mongoc_session_opt_t *opts, const mongoc_transaction_opt_t *txn_opts);
Set the default options for transactions started with this session. The
txn_opts argument is copied and can be freed after calling this func-
tion.
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_session_opts_set_default_transaction_opts(). Each field set in
the transaction options overrides the inherited client configuration.
There is an opportunity to override each one of these fields again by
passing a mongoc_transaction_opt_t to
mongoc_client_session_start_transaction().
PARAMETERS
+ opts: A mongoc_session_opt_t.
+ txn_opts: A mongoc_transaction_opt_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOCMayS12,N2025S_SET_DEFAULT_TRANSACTION_OPTS(3)
mongoc_session_opts_set_snapshot.3
MONGOC_SESSION_OPTS_SET_SNAPSHOT(3)libmongocONGOC_SESSION_OPTS_SET_SNAPSHOT(3)
SYNOPSIS
void
mongoc_session_opts_set_snapshot (mongoc_session_opt_t *opts,
bool snapshot);
Configure snapshot reads for a session. If true (false by default),
each read operation in the session will be sent with a "snapshot" level
read concern. After the first read operation ("find", "aggregate" or
"distinct"), subsequent read operations will read from the same point
in time as the first read operation. Set to true to enable snapshot
reads. See the official documentation for Read Concern "snapshot".
Snapshot reads and causal consistency are mutually exclusive. Attempt-
ing to set both to true will result in an error. See
mongoc_session_opts_set_causal_consistency().
Snapshot reads can only be used on MongoDB server version 5.0 and later
and cannot be used during a transaction. A write operation in a snap-
shot-enabled session will also result in an error.
PARAMETERS
+ opts: A mongoc_session_opt_t.
+ snapshot: True or false.
EXAMPLE
mongoc_client_t *client;
mongoc_session_opt_t *session_opts;
mongoc_client_session_t *client_session;
mongoc_collection_t *collection;
bson_t query_opts = BSON_INITIALIZER;
bson_t filter = BSON_INITIALIZER;
bson_t pipeline = BSON_INITIALIZER;
client = mongoc_client_new ("mongodb://example/?appname=session-opts-example");
mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2);
session_opts = mongoc_session_opts_new ();
mongoc_session_opts_set_snapshot (session_opts, true);
client_session = mongoc_client_start_session (client, session_opts, &error);
mongoc_session_opts_destroy (session_opts);
if (!client_session) {
fprintf (stderr, "Failed to start session: %s\n", error.message);
abort ();
}
collection = mongoc_client_get_collection (client, "test", "collection");
r = mongoc_client_session_append (client_session, &find_opts, &error);
if (!r) {
fprintf (stderr, "mongoc_client_session_append failed: %s\n", error.message);
abort ();
}
/* First read operation will set the snapshot time for subsequent reads. */
cursor = mongoc_collection_find_with_opts (collection, filter, &query_opts, NULL);
/* Subsequent read operations will automatically read from the same point
* in time as the first read operation. */
cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, &query_opts, NULL);
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_SESSION_OPTS_SET_SNAPSHOT(3)
mongoc_socket_accept.3
MONGOC_SOCKET_ACCEPT(3) libmongoc MONGOC_SOCKET_ACCEPT(3)
SYNOPSIS
mongoc_socket_t *
mongoc_socket_accept (mongoc_socket_t *sock,
int64_t expire_at);
PARAMETERS
+ sock: A mongoc_socket_t.
+ expire_at: An int64_t containing a timeout in milliseconds.
DESCRIPTION
This function is a wrapper around the BSD socket accept() interface. It
allows for more portability between UNIX-like and Microsoft Windows
platforms.
RETURNS
NULL upon failure to accept or timeout. A newly allocated mon-
goc_socket_t that should be released with mongoc_socket_destroy() on
success.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_ACCEPT(3)
mongoc_socket_bind.3
MONGOC_SOCKET_BIND(3) libmongoc MONGOC_SOCKET_BIND(3)
SYNOPSIS
int
mongoc_socket_bind (mongoc_socket_t *sock,
const struct sockaddr *addr,
mongoc_socklen_t addrlen);
PARAMETERS
+ sock: A mongoc_socket_t.
+ addr: A struct sockaddr.
+ addrlen: A mongoc_socklen_t.
DESCRIPTION
This function is a wrapper around the BSD socket bind() interface. It
provides better portability between UNIX-like and Microsoft Windows
platforms.
RETURNS
0 on success, -1 on failure and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_BIND(3)
mongoc_socket_close.3
MONGOC_SOCKET_CLOSE(3) libmongoc MONGOC_SOCKET_CLOSE(3)
SYNOPSIS
int
mongoc_socket_close (mongoc_socket_t *socket);
PARAMETERS
+ socket: A mongoc_socket_t.
DESCRIPTION
This function is a wrapper around the BSD socket shutdown() and close()
functions, and their Windows equivalents. The socket is shut down only
if the current process is the same as the process that opened the
socket. Regardless, the socket is then closed.
RETURNS
0 on success, -1 on failure to close the socket. On failure, the
socket's errno is set; retrieve it with mongoc_socket_errno().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_CLOSE(3)
mongoc_socket_connect.3
MONGOC_SOCKET_CONNECT(3) libmongoc MONGOC_SOCKET_CONNECT(3)
SYNOPSIS
int
mongoc_socket_connect (mongoc_socket_t *sock,
const struct sockaddr *addr,
mongoc_socklen_t addrlen,
int64_t expire_at);
PARAMETERS
+ sock: A mongoc_socket_t.
+ addr: A struct sockaddr.
+ addrlen: A mongoc_socklen_t.
+ expire_at: A int64_t containing the absolute timeout using the mono-
tonic clock.
DESCRIPTION
This function is a wrapper around the BSD socket connect() interface.
It provides better portability between UNIX-like and Microsoft Windows
platforms.
This function performs a socket connection but will fail if expire_at
has been reached by the monotonic clock. Keep in mind that this is an
absolute timeout in milliseconds. You should add your desired timeout
to System Clock.
RETURNS
0 if successful, -1 on failure and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_CONNECT(3)
mongoc_socket_destroy.3
MONGOC_SOCKET_DESTROY(3) libmongoc MONGOC_SOCKET_DESTROY(3)
SYNOPSIS
void
mongoc_socket_destroy (mongoc_socket_t *sock);
PARAMETERS
+ sock: A mongoc_socket_t.
DESCRIPTION
This function releases all resources associated with a mongoc_socket_t.
This should be called when you are no longer using the socket. Does
nothing if sock is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_DESTROY(3)
mongoc_socket_errno.3
MONGOC_SOCKET_ERRNO(3) libmongoc MONGOC_SOCKET_ERRNO(3)
SYNOPSIS
int
mongoc_socket_errno (mongoc_socket_t *sock);
PARAMETERS
+ sock: A mongoc_socket_t.
DESCRIPTION
This function returns the currently captured errno for a socket. This
may be useful to check was the last errno was after another function
call has been made that clears the threads errno variable.
RETURNS
0 if there is no error, otherwise a specific errno.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_ERRNO(3)
mongoc_socket_getnameinfo.3
MONGOC_SOCKET_GETNAMEINFO(3) libmongoc MONGOC_SOCKET_GETNAMEINFO(3)
SYNOPSIS
char *
mongoc_socket_getnameinfo (mongoc_socket_t *sock);
PARAMETERS
+ sock: A mongoc_socket_t.
DESCRIPTION
This is a helper around getting the local name of a socket. It is a
wrapper around getpeername() and getnameinfo().
RETURNS
A newly allocated string that should be freed with bson_free().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_GETNAMEINFO(3)
mongoc_socket_getsockname.3
MONGOC_SOCKET_GETSOCKNAME(3) libmongoc MONGOC_SOCKET_GETSOCKNAME(3)
SYNOPSIS
int
mongoc_socket_getsockname (mongoc_socket_t *sock,
struct sockaddr *addr,
mongoc_socklen_t *addrlen);
PARAMETERS
+ sock: A mongoc_socket_t.
+ addr: A struct sockaddr.
+ addrlen: A mongoc_socklen_t.
DESCRIPTION
Retrieves the socket name for sock. The result is stored in addr. ad-
drlen should be the size of the addr when calling this.
RETURNS
0 if successful, otherwise -1 and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_GETSOCKNAME(3)
mongoc_socket_listen.3
MONGOC_SOCKET_LISTEN(3) libmongoc MONGOC_SOCKET_LISTEN(3)
SYNOPSIS
int
mongoc_socket_listen (mongoc_socket_t *sock, unsigned int backlog);
PARAMETERS
+ sock: A mongoc_socket_t.
+ backlog: An int containing max backlog size.
DESCRIPTION
This function is similar to the BSD sockets listen() function. It is
meant for socket servers.
RETURNS
0 on success, -1 on failure and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_LISTEN(3)
mongoc_socket_new.3
MONGOC_SOCKET_NEW(3) libmongoc MONGOC_SOCKET_NEW(3)
SYNOPSIS
mongoc_socket_t *
mongoc_socket_new (int domain,
int type,
int protocol);
PARAMETERS
+ domain: An int containing the address family such as AF_INET.
+ type: An int containing the socket type such as SOCK_STREAM.
+ protocol: A protocol subset, typically 0.
DESCRIPTION
Creates a new mongoc_socket_t structure. This calls socket() underneath
to create a network socket.
RETURNS
A new socket if successful, otherwise NULL and errno is set. The result
should be freed with mongoc_socket_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_NEW(3)
mongoc_socket_recv.3
MONGOC_SOCKET_RECV(3) libmongoc MONGOC_SOCKET_RECV(3)
SYNOPSIS
ssize_t
mongoc_socket_recv (mongoc_socket_t *sock,
void *buf,
size_t buflen,
int flags,
int64_t expire_at);
PARAMETERS
+ sock: A mongoc_socket_t.
+ buf: A buffer to read into.
+ buflen: A size_t with the number of bytes to receive.
+ flags: flags for recv().
+ expire_at: A int64_t with the time to expire in monotonic time using
System Clock, which is in microseconds.
DESCRIPTION
This function performs a recv() on the underlying socket.
RETURNS
The number of bytes received on success, 0 on stream closed, and -1 if
there was a failure and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_RECV(3)
mongoc_socket_send.3
MONGOC_SOCKET_SEND(3) libmongoc MONGOC_SOCKET_SEND(3)
SYNOPSIS
ssize_t
mongoc_socket_send (mongoc_socket_t *sock,
const void *buf,
size_t buflen,
int64_t expire_at);
PARAMETERS
+ sock: A mongoc_socket_t.
+ buf: A buffer to send.
+ buflen: A size_t with the number of bytes in buf.
+ expire_at: A int64_t with an absolute timeout for the operation or 0.
The timeout is in monotonic time using microseconds. You can retrieve
the current monotonic time with System Clock.
DESCRIPTION
Sends buflen bytes in buf to the destination. If a timeout expired, the
number of bytes sent will be returned or -1 if no bytes were sent.
RETURNS
-1 on failure and errno is set, or the number of bytes sent.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_SEND(3)
mongoc_socket_sendv.3
MONGOC_SOCKET_SENDV(3) libmongoc MONGOC_SOCKET_SENDV(3)
SYNOPSIS
ssize_t
mongoc_socket_sendv (mongoc_socket_t *sock,
mongoc_iovec_t *iov,
size_t iovcnt,
int64_t expire_at);
PARAMETERS
+ sock: A mongoc_socket_t.
+ iov: A mongoc_iovec_t.
+ iovcnt: A size_t containing the number of elements in iov.
+ expire_at: A int64_t with absolute timeout in monotonic time. The
monotonic clock is in microseconds and can be fetched using System
Clock.
DESCRIPTION
Sends a vector of buffers to the destination. This uses sendmsg() when
available to perform a gathered write. If IOV_MAX is reached, a fall-
back will be used.
RETURNS
the number of bytes sent on success, or -1 on failure and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_SENDV(3)
mongoc_socket_setsockopt.3
MONGOC_SOCKET_SETSOCKOPT(3) libmongoc MONGOC_SOCKET_SETSOCKOPT(3)
SYNOPSIS
int
mongoc_socket_setsockopt (mongoc_socket_t *sock,
int level,
int optname,
const void *optval,
mongoc_socklen_t optlen);
PARAMETERS
+ sock: A mongoc_socket_t.
+ level: A sockopt level.
+ optname: A sockopt name.
+ optval: A the value for the sockopt.
+ optlen: A mongoc_socklen_t that contains the length of optval.
DESCRIPTION
This is a helper function for setsockopt().
RETURNS
0 on success, -1 on failure and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_SETSOCKOPT(3)
mongoc_socket_t.3
MONGOC_SOCKET_T(3) libmongoc MONGOC_SOCKET_T(3)
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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SOCKET_T(3)
mongoc_ssl_opt_get_default.3
MONGOC_SSL_OPT_GET_DEFAULT(3) libmongoc MONGOC_SSL_OPT_GET_DEFAULT(3)
SYNOPSIS
const mongoc_ssl_opt_t *
mongoc_ssl_opt_get_default (void);
NOTE:
Though some API names include the term "ssl", the C driver only sup-
port TLS protocols, which supersede SSL.
RETURNS
Returns the default TLS options for the process. This should not be
modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SSL_OPT_GET_DEFAULT(3)
mongoc_ssl_opt_t.3
MONGOC_SSL_OPT_T(3) libmongoc MONGOC_SSL_OPT_T(3)
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 sup-
port TLS protocols, which supersede SSL.
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 Mon-
goDB 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()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_SSL_OPT_T(3)
mongoc_stream_buffered_new.3
MONGOC_STREAM_BUFFERED_NEW(3) libmongoc MONGOC_STREAM_BUFFERED_NEW(3)
SYNOPSIS
mongoc_stream_t *
mongoc_stream_buffered_new (mongoc_stream_t *base_stream,
size_t buffer_size);
PARAMETERS
+ base_stream: A mongoc_stream_t to buffer.
+ buffer_size: A size_t containing the desired buffer size.
This function shall create a new mongoc_stream_t that buffers bytes to
and from the underlying base_stream.
buffer_size will be used as the initial buffer size. It may grow past
this size.
RETURNS
A newly allocated mongoc_stream_buffered_t on success, otherwise NULL.
This should be freed with mongoc_stream_destroy() when no longer in
use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_BUFFERED_NEW(3)
mongoc_stream_buffered_t.3
MONGOC_STREAM_BUFFERED_T(3) libmongoc MONGOC_STREAM_BUFFERED_T(3)
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()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_BUFFERED_T(3)
mongoc_stream_close.3
MONGOC_STREAM_CLOSE(3) libmongoc MONGOC_STREAM_CLOSE(3)
SYNOPSIS
int
mongoc_stream_close (mongoc_stream_t *stream);
PARAMETERS
+ stream: A mongoc_stream_t.
This function shall close underlying file-descriptors of stream.
RETURNS
0 on success, otherwise -1 and errno is set.
SEE ALSO:
mongoc_stream_destroy()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_CLOSE(3)
mongoc_stream_cork.3
MONGOC_STREAM_CORK(3) libmongoc MONGOC_STREAM_CORK(3)
SYNOPSIS
int
mongoc_stream_cork (mongoc_stream_t *stream);
PARAMETERS
+ stream: A mongoc_stream_t.
This function shall prevent the writing of bytes to the underlying
socket.
NOTE:
Not all streams implement this function. Buffering generally works
better.
RETURNS
0 on success, -1 on failure and errno is set.
SEE ALSO:
mongoc_stream_buffered_new().
mongoc_stream_uncork().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_CORK(3)
mongoc_stream_destroy.3
MONGOC_STREAM_DESTROY(3) libmongoc MONGOC_STREAM_DESTROY(3)
SYNOPSIS
void
mongoc_stream_destroy (mongoc_stream_t *stream);
PARAMETERS
+ stream: A mongoc_stream_t.
This function shall release all resources associated with a
mongoc_stream_t, including freeing the structure. It is invalid to use
stream after calling this function. Does nothing if stream is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_DESTROY(3)
mongoc_stream_file_get_fd.3
MONGOC_STREAM_FILE_GET_FD(3) libmongoc MONGOC_STREAM_FILE_GET_FD(3)
SYNOPSIS
int
mongoc_stream_file_get_fd (mongoc_stream_file_t *stream);
PARAMETERS
+ stream: A mongoc_stream_file_t.
This function shall return the underlying file-descriptor of a
mongoc_stream_file_t.
WARNING:
Performing operations on the underlying file-descriptor may not be
safe if used in conjunction with buffering. Avoid reading or writing
from this file-descriptor.
RETURNS
A file-descriptor that should not be modified by the caller.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_FILE_GET_FD(3)
mongoc_stream_file_new.3
MONGOC_STREAM_FILE_NEW(3) libmongoc MONGOC_STREAM_FILE_NEW(3)
SYNOPSIS
mongoc_stream_t *
mongoc_stream_file_new (int fd);
PARAMETERS
+ fd: A UNIX style file-descriptor.
Creates a new mongoc_stream_file_t using the file-descriptor provided.
RETURNS
NULL upon failure, otherwise a newly allocated mongoc_stream_file_t
that should be freed with mongoc_stream_destroy() when no longer in
use.
errno is set upon failure.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_FILE_NEW(3)
mongoc_stream_file_new_for_path.3
MONGOC_STREAM_FILE_NEW_FOR_PATH(3) libmongocMONGOC_STREAM_FILE_NEW_FOR_PATH(3)
SYNOPSIS
mongoc_stream_t *
mongoc_stream_file_new_for_path (const char *path,
int flags,
int mode);
PARAMETERS
+ path: The path of the target file.
+ flags: Flags to be passed to open().
+ mode: An optional mode to be passed to open() when creating a file.
This function shall create a new mongoc_stream_file_t after opening the
underlying file with open() or the platform equivalent.
RETURNS
NULL on failure, otherwise a newly allocated mongoc_stream_file_t that
should be freed with mongoc_stream_destroy() when no longer in use.
errno is set upon failure.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_STREAM_FILE_NEW_FOR_PATH(3)
mongoc_stream_file_t.3
MONGOC_STREAM_FILE_T(3) libmongoc MONGOC_STREAM_FILE_T(3)
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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_FILE_T(3)
mongoc_stream_flush.3
MONGOC_STREAM_FLUSH(3) libmongoc MONGOC_STREAM_FLUSH(3)
SYNOPSIS
int
mongoc_stream_flush (mongoc_stream_t *stream);
PARAMETERS
+ stream: A mongoc_stream_t.
This function shall flush any buffered bytes in the underlying stream
to the physical transport. It mimics the API and semantics of fflush(),
forcing a write of user space buffered data.
Not all stream implementations may implement this feature.
RETURNS
0 is returned on success, otherwise -1 and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_FLUSH(3)
mongoc_stream_get_base_stream.3
MONGOC_STREAM_GET_BASE_STREAM(3) libmongoc MONGOC_STREAM_GET_BASE_STREAM(3)
SYNOPSIS
mongoc_stream_t *
mongoc_stream_get_base_stream (mongoc_stream_t *stream);
PARAMETERS
+ stream: A mongoc_stream_t.
This function shall fetch the underlying stream for streams that wrap a
base stream. Such implementations include mongoc_stream_buffered_t and
mongoc_stream_tls_t.
RETURNS
A mongoc_stream_t or NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_GET_BASE_STREAM(3)
mongoc_stream_gridfs_new.3
MONGOC_STREAM_GRIDFS_NEW(3) libmongoc MONGOC_STREAM_GRIDFS_NEW(3)
SYNOPSIS
mongoc_stream_t *
mongoc_stream_gridfs_new (mongoc_gridfs_file_t *file);
PARAMETERS
+ file: A mongoc_gridfs_file_t.
This function shall create a new mongoc_stream_t to read from and write
to a GridFS file. GridFS files are created with
mongoc_gridfs_create_file() or mongoc_gridfs_create_file_from_stream().
This function does not transfer ownership of file. Therefore, file must
remain valid for the lifetime of this stream.
RETURNS
A newly allocated mongoc_stream_t if successful, otherwise NULL.
Note, the returned stream ignores read and write timeouts passed to
mongoc_stream_readv(), mongoc_stream_writev(), and so on. It uses the
"socketTimeoutMS" and "connectTimeoutMS" values from the MongoDB URI.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_GRIDFS_NEW(3)
mongoc_stream_read.3
MONGOC_STREAM_READ(3) libmongoc MONGOC_STREAM_READ(3)
SYNOPSIS
ssize_t
mongoc_stream_read (mongoc_stream_t *stream,
void *buf,
size_t count,
size_t min_bytes,
int32_t timeout_msec);
PARAMETERS
+ stream: A mongoc_stream_t.
+ buf: The buffer to read into.
+ count: The number of bytes to read.
+ min_bytes: The minimum number of bytes to read, or else indicate
failure.
+ timeout_msec: The number of milliseconds to wait before failure, a
timeout of 0 will not block. If negative, use the default timeout.
The mongoc_stream_read() function shall perform a read from a
mongoc_stream_t. It's modeled on the API and semantics of read(),
though the parameters map only loosely.
WARNING:
The "default timeout" indicated by a negative value is both unspeci-
fied and unrelated to the documented default values for *TimeoutMS
URI options. To specify a default timeout value for a *TimeoutMS
URI option, use the MONGOC_DEFAULT_* constants defined in mon-
goc-client.h.
RETURNS
The mongoc_stream_read() function returns the number of bytes read on
success. It returns >= 0 and < min_bytes when end-of-file is encoun-
tered and -1 on failure. errno is set upon failure.
SEE ALSO:
mongoc_stream_readv()
mongoc_stream_write()
mongoc_stream_writev()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_READ(3)
mongoc_stream_readv.3
MONGOC_STREAM_READV(3) libmongoc MONGOC_STREAM_READV(3)
SYNOPSIS
ssize_t
mongoc_stream_readv (mongoc_stream_t *stream,
mongoc_iovec_t *iov,
size_t iovcnt,
size_t min_bytes,
int32_t timeout_msec);
PARAMETERS
+ stream: A mongoc_stream_t.
+ iov: A vector of mongoc_iovec_t.
+ iovcnt: The number of items in iov.
+ min_bytes: The minimum number of bytes to read or failure will be in-
dicated.
+ timeout_msec: A timeout in milliseconds, or 0 to indicate non-block-
ing. A negative value with use the default timeout.
This function is identical to mongoc_stream_read() except that it takes
a mongoc_iovec_t to perform gathered I/O.
WARNING:
The "default timeout" indicated by a negative value is both unspeci-
fied and unrelated to the documented default values for *TimeoutMS
URI options. To specify a default timeout value for a *TimeoutMS
URI option, use the MONGOC_DEFAULT_* constants defined in mon-
goc-client.h.
RETURNS
>= 0 on success, -1 on failure and errno is set.
SEE ALSO:
mongoc_stream_read()
mongoc_stream_write()
mongoc_stream_writev()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_READV(3)
mongoc_stream_setsockopt.3
MONGOC_STREAM_SETSOCKOPT(3) libmongoc MONGOC_STREAM_SETSOCKOPT(3)
SYNOPSIS
int
mongoc_stream_setsockopt (mongoc_stream_t *stream,
int level,
int optname,
void *optval,
mongoc_socklen_t optlen);
PARAMETERS
+ stream: A mongoc_stream_t.
+ level: The level to pass to setsockopt().
+ optname: The optname to pass to setsockopt().
+ optval: The optval to pass to setsockopt().
+ optlen: The optlen to pass to setsockopt().
This function is a wrapper around setsockopt() for streams that wrap
sockets.
RETURNS
0 on success, otherwise -1 and errno is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_SETSOCKOPT(3)
mongoc_stream_should_retry.3
MONGOC_STREAM_SHOULD_RETRY(3) libmongoc MONGOC_STREAM_SHOULD_RETRY(3)
SYNOPSIS
bool
mongoc_stream_should_retry (mongoc_stream_t *stream);
PARAMETERS
+ stream: A mongoc_stream_t.
RETURNS
True if the stream is open and has encountered a retryable network er-
ror such as EAGAIN or if a TLS exchange is in progress and needs more
data.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_SHOULD_RETRY(3)
mongoc_stream_socket_get_socket.3
MONGOC_STREAM_SOCKET_GET_SOCKET(3) libmongocMONGOC_STREAM_SOCKET_GET_SOCKET(3)
SYNOPSIS
mongoc_socket_t *
mongoc_stream_socket_get_socket (mongoc_stream_socket_t *stream);
PARAMETERS
+ stream: A mongoc_stream_socket_t.
Retrieves the underlying mongoc_socket_t for a mongoc_stream_socket_t.
RETURNS
A mongoc_stream_socket_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_STREAM_SOCKET_GET_SOCKET(3)
mongoc_stream_socket_new.3
MONGOC_STREAM_SOCKET_NEW(3) libmongoc MONGOC_STREAM_SOCKET_NEW(3)
SYNOPSIS
mongoc_stream_t *
mongoc_stream_socket_new (mongoc_socket_t *socket);
PARAMETERS
+ socket: A mongoc_socket_t.
Creates a new mongoc_stream_socket_t using the mongoc_socket_t pro-
vided.
WARNING:
This function transfers ownership of socket to the newly allocated
stream.
RETURNS
A newly allocated mongoc_stream_socket_t that should be freed with
mongoc_stream_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_SOCKET_NEW(3)
mongoc_stream_socket_t.3
MONGOC_STREAM_SOCKET_T(3) libmongoc MONGOC_STREAM_SOCKET_T(3)
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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_SOCKET_T(3)
mongoc_stream_t.3
MONGOC_STREAM_T(3) libmongoc MONGOC_STREAM_T(3)
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 mon-
goc_stream_t.
The API for the stream abstraction is currently private and non-exten-
sible.
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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_T(3)
mongoc_stream_timed_out.3
MONGOC_STREAM_TIMED_OUT(3) libmongoc MONGOC_STREAM_TIMED_OUT(3)
SYNOPSIS
bool
mongoc_stream_timed_out (mongoc_stream_t *stream);
PARAMETERS
+ stream: A mongoc_stream_t.
RETURNS
True if there has been a network timeout error on this stream.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_TIMED_OUT(3)
mongoc_stream_tls_t.3
MONGOC_STREAM_TLS_T(3) libmongoc MONGOC_STREAM_TLS_T(3)
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.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_TLS_T(3)
mongoc_stream_uncork.3
MONGOC_STREAM_UNCORK(3) libmongoc MONGOC_STREAM_UNCORK(3)
SYNOPSIS
int
mongoc_stream_uncork (mongoc_stream_t *stream);
PARAMETERS
+ stream: A mongoc_stream_t.
This function shall allow a previously corked socket to pass bytes to
the underlying socket.
NOTE:
Not all streams implement this function. Buffering generally works
better.
RETURNS
0 on success, -1 on failure and errno is set.
SEE ALSO:
mongoc_stream_buffered_new().
mongoc_stream_cork().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_UNCORK(3)
mongoc_stream_write.3
MONGOC_STREAM_WRITE(3) libmongoc MONGOC_STREAM_WRITE(3)
SYNOPSIS
ssize_t
mongoc_stream_write (mongoc_stream_t *stream,
void *buf,
size_t count,
int32_t timeout_msec);
PARAMETERS
+ stream: A mongoc_stream_t.
+ buf: The buffer to write.
+ count: The number of bytes to write.
+ timeout_msec: The number of milliseconds to wait before failure, a
timeout of 0 will not block. If negative, use the default timeout.
The mongoc_stream_write() function shall perform a write to a
mongoc_stream_t. It's modeled on the API and semantics of write(),
though the parameters map only loosely.
WARNING:
The "default timeout" indicated by a negative value is both unspeci-
fied and unrelated to the documented default values for *TimeoutMS
URI options. To specify a default timeout value for a *TimeoutMS
URI option, use the MONGOC_DEFAULT_* constants defined in mon-
goc-client.h.
RETURNS
The mongoc_stream_write() function returns the number of bytes written
on success. It returns -1 and sets errno upon failure.
SEE ALSO:
mongoc_stream_read()
mongoc_stream_readv()
mongoc_stream_writev()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_WRITE(3)
mongoc_stream_writev.3
MONGOC_STREAM_WRITEV(3) libmongoc MONGOC_STREAM_WRITEV(3)
SYNOPSIS
ssize_t
mongoc_stream_writev (mongoc_stream_t *stream,
mongoc_iovec_t *iov,
size_t iovcnt,
int32_t timeout_msec);
PARAMETERS
+ stream: A mongoc_stream_t.
+ iov: A vector of mongoc_iovec_t.
+ iovcnt: The number of items in iov.
+ timeout_msec: The number of milliseconds to block before indicating
failure, or 0 for non-blocking. Negative values indicate the default
timeout.
The mongoc_stream_writev() function shall perform a write to a
mongoc_stream_t. It's modeled on the API and semantics of writev(),
though the parameters map only loosely.
WARNING:
The "default timeout" indicated by a negative value is both unspeci-
fied and unrelated to the documented default values for *TimeoutMS
URI options. To specify a default timeout value for a *TimeoutMS
URI option, use the MONGOC_DEFAULT_* constants defined in mon-
goc-client.h.
RETURNS
The number of bytes written on success, or -1 upon failure and errno is
set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STREAM_WRITEV(3)
mongoc_structured_log.3
MONGOC_STRUCTURED_LOG(3) libmongoc MONGOC_STRUCTURED_LOG(3)
This document describes a newer "structured" logging facility which reports
messages from the driver itself using a BSON format defined across driver im-
plementations 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().
OPTIONS
Structured log settings are tracked explicitly by a
mongoc_structured_log_opts_t instance.
Like other drivers supporting structured logging, we take default set-
tings from environment variables and offer additional optional program-
matic 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 pro-
grammatic 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 han-
dler, 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 maxi-
mum 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().
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 cap-
tured 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 warn-
ings 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 implementa-
tion-specific value near the maximum representable length. By de-
fault, the limit is 1000 bytes. This limit affects interior docu-
ments 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:
When a file path is given for MONGODB_LOG_PATH, each log instance
(one stand-alone client or pool) will separately open this file
for append. The results are operating system specific. On
UNIX-like platforms each instance's output will be interleaved, in
most cases without splitting individual log messages. Notably on
Windows the file will be opened in exclusive mode by the first in-
stance and subsequent instances will fail, falling back on the de-
fault of stderr. Applications that use multiple processes or mul-
tiple client pools will likely want to supply a log handler that
annotates each message with information about its originating log
instance.
+ MONGODB_LOG_COMMAND: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_COMMAND.
+ MONGODB_LOG_TOPOLOGY: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_TOPOLOGY.
+ MONGODB_LOG_SERVER_SELECTION: A log level name to set as the maximum
for MONGOC_STRUCTURED_LOG_COMPONENT_SERVER_SELECTION.
+ MONGODB_LOG_CONNECTION: A log level name to set as the maximum for
MONGOC_STRUCTURED_LOG_COMPONENT_CONNECTION.
+ MONGODB_LOG_ALL: A log level name applied to all components not oth-
erwise specified.
Note that log level names are always case insensitive. This is a full
list of recognized names, including allowed aliases:
+ 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 allocated with
mongoc_structured_log_opts_new(), or NULL.
Description
This function releases all resources associated with a
mongoc_structured_log_opts_t. Does nothing if opts is NULL.
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 to be called to handle structured log messages, as a
mongoc_structured_log_func_t.
The callback is given a mongoc_structured_log_entry_t as a handle for
obtaining additional information about the log message. This entry
pointer is only valid during a callback, because it's a low cost refer-
ence to temporary data.
Structured log handlers must be thread-safe if they will be used with
mongoc_client_pool_t. Handlers must avoid unbounded recursion, prefer-
ably by avoiding the use of any libmongoc client or pool which uses the
same handler.
This function always replaces the default log handler from
mongoc_structured_log_opts_new(), if it was still set. If the log_func
is set to NULL, structured logging will be disabled.
Parameters
+ opts: Structured log options, allocated with
mongoc_structured_log_opts_new().
+ log_func: The handler to install, a mongoc_structured_log_func_t, or
NULL to disable structured logging.
+ user_data: Optional user data, passed on to the 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 be-
low this severity level will be passed to mongoc_structured_log_func_t.
By default, each component's log level may come from environment vari-
ables. 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 to set 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 supplied parameters were in-
correct.
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 all per-component maximum log levels to the same value. Only log
messages at or below this severity level will be passed to
mongoc_structured_log_func_t. Effective even for logging components
not known at compile-time.
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 in-
correct.
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 requested by environment variables: MON-
GODB_LOG_ALL for all components, followed by per-component log levels
MONGODB_LOG_COMMAND, MONGODB_LOG_CONNECTION, MONGODB_LOG_TOPOLOGY, and
MONGODB_LOG_SERVER_SELECTION.
Expects the value to be recognizable by
mongoc_structured_log_get_named_level(). Parse errors may cause a
warning message, delivered via unstructured logging.
Component levels with no valid environment variable setting will be
left unmodified.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may 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(). This
will process the environment a second time, allowing it to override
customized defaults.
Returns
Returns true on success. If warnings are encountered in the environ-
ment, returns false and may log additional information to the unstruc-
tured logging facility. Note that, by design, these errors are by de-
fault 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_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 a specific component, as a
mongoc_structured_log_level_t. This may 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
may be the default obtained from environment variables. If an invalid
or unknown component enum is given, returns the lowest log level.
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 appear serialized in JSON
form as part of a structured log message.
Serialized JSON will be truncated at this limit, interpreted as a count
of UTF-8 encoded bytes. Truncation will be indicated with a ... suffix,
the length of which is not included in the max document length. If
truncation at the exact indicated length would split a valid UTF-8 se-
quence, we instead truncate the document earlier at the nearest bound-
ary between code points.
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 trunca-
tion. Values near or above INT_MAX will be rejected.
Returns
Returns true on success, or false if the supplied maximum length 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 a description of the supported en-
vironment variable formats.
Parse errors may cause a warning message, delivered via unstructured
logging.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may call
mongoc_structured_log_opts_set_max_document_length_from_env() after
calling mongoc_structured_log_opts_set_max_document_length(). This
will process the environment a second time, allowing it to override
customized defaults.
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 de-
sign, these errors are by default non-fatal. When
mongoc_structured_log_opts_new() internally calls this function, it ig-
nores 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 set in opts, as a size_t.
SEE ALSO:
Structured Logging
SEE ALSO:
Structured Logging
LEVELS AND COMPONENTS
Log levels and components are defined as mongoc_structured_log_level_t
and mongoc_structured_log_component_t enumerations. Utilities are pro-
vided to convert between these values and their standard string repre-
sentations. The string values are case-insensitive.
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 the available log levels for
use with structured logging.
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, returns a pointer to a constant string that
should not be freed. If the level has no known name, 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.
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, returns true and writes the level enum to
*out. If the level name is not known, returns false and does not write
*out.
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. Applications should never rely on having an exhaustive
list of all log components. Instead, use
mongoc_structured_log_opts_set_max_level_for_all_components() to set a
default level if needed.
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.
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, returns true and writes the component
enum to *out. If the component name is not known, returns false and
does not write *out.
SEE ALSO:
Structured Logging
SEE ALSO:
Structured Logging
SEE ALSO:
mongoc_structured_log_get_level_name mongoc_struc-
tured_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 in-
stance of the structured logging subsystem, with its own settings and
handler.
When using mongoc_client_pool_t, the pooled clients all share a common
logging instance. Handlers must be thread-safe.
The handler is called for each log entry with a level no greater than
its component's maximum. A mongoc_structured_log_entry_t pointer pro-
vides access to further details, during the handler only.
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.
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(). Struc-
tured log handlers must be thread-safe if they will be used with
mongoc_client_pool_t. Handlers must avoid unbounded recursion, prefer-
ably by avoiding the use of any libmongoc client or pool which uses the
same handler.
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 within the handler by a short-lived
mongoc_structured_log_entry_t pointer. During the handler, this
pointer can be used to access the individual properties of an entry:
its level, component, and message.
The message will be assembled as a bson_t only when explicitly re-
quested by a call to mongoc_structured_log_entry_message_as_bson().
This results in a standalone document that may be retained for any
amount of time and must be explicitly destroyed.
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 which represents
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 individual aspects
of the log entry.
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 struc-
tured log handler. It should not be freed or modified.
Identical to the value of the message key in the document returned by
mongoc_structured_log_entry_message_as_bson().
This is not a complete string representation of the structured log, but
rather a standardized identifier for a particular log event.
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 rep-
resentation. When possible, a log handler should avoid serializing log
messages that will be discarded. 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
/* 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 proceses 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_en-
try_get_level mongoc_structured_log_entry_message_as_bson
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STRUCTURED_LOG(3)
mongoc_structured_log_component_t.3
MONGOC_STRUCTURED_LOG_COMPONENT_T(3)ibmongocNGOC_STRUCTURED_LOG_COMPONENT_T(3)
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. Applications should never rely on having an exhaustive
list of all log components. Instead, use
mongoc_structured_log_opts_set_max_level_for_all_components() to set a
default level if needed.
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.
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, returns true and writes the component
enum to *out. If the component name is not known, returns false and
does not write *out.
SEE ALSO:
Structured Logging
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_STRUCTURED_LOG_COMPONENT_T(3)
mongoc_structured_log_entry_get_component.3
MONGOC_STRUCTURED_LOG_ENTRY_GET_COMPONENT(3)UCTURED_LOG_ENTRY_GET_COMPONENT(3)
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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025CTURED_LOG_ENTRY_GET_COMPONENT(3)
mongoc_structured_log_entry_get_level.3
MONGOC_STRUCTURED_LOG_ENTRY_GET_LEVEL(3)ngoc_STRUCTURED_LOG_ENTRY_GET_LEVEL(3)
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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025STRUCTURED_LOG_ENTRY_GET_LEVEL(3)
mongoc_structured_log_entry_get_message_string.3
MONGOC_STRUCTURED_LOG_ENTRY_GETNMESSAGEoSTRING(3)G_ENTRY_GET_MESSAGE_STRING(3)
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 struc-
tured log handler. It should not be freed or modified.
Identical to the value of the message key in the document returned by
mongoc_structured_log_entry_message_as_bson().
This is not a complete string representation of the structured log, but
rather a standardized identifier for a particular log event.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayS12,C2025D_LOG_ENTRY_GET_MESSAGE_STRING(3)
mongoc_structured_log_entry_message_as_bson.3
MONGOC_STRUCTURED_LOG_ENTRY_MESSAGElASmBSON(3)RED_LOG_ENTRY_MESSAGE_AS_BSON(3)
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 rep-
resentation. When possible, a log handler should avoid serializing log
messages that will be discarded. 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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MMayO12,T2025URED_LOG_ENTRY_MESSAGE_AS_BSON(3)
mongoc_structured_log_entry_t.3
MONGOC_STRUCTURED_LOG_ENTRY_T(3) libmongoc MONGOC_STRUCTURED_LOG_ENTRY_T(3)
SYNOPSIS
typedef struct mongoc_structured_log_entry_t mongoc_structured_log_entry_t;
mongoc_structured_log_entry_t is an opaque structure which represents
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 individual aspects
of the log entry.
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 struc-
tured log handler. It should not be freed or modified.
Identical to the value of the message key in the document returned by
mongoc_structured_log_entry_message_as_bson().
This is not a complete string representation of the structured log, but
rather a standardized identifier for a particular log event.
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 rep-
resentation. When possible, a log handler should avoid serializing log
messages that will be discarded. 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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STRUCTURED_LOG_ENTRY_T(3)
mongoc_structured_log_func_t.3
MONGOC_STRUCTURED_LOG_FUNC_T(3) libmongoc MONGOC_STRUCTURED_LOG_FUNC_T(3)
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(). Struc-
tured log handlers must be thread-safe if they will be used with
mongoc_client_pool_t. Handlers must avoid unbounded recursion, prefer-
ably by avoiding the use of any libmongoc client or pool which uses the
same handler.
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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STRUCTURED_LOG_FUNC_T(3)
mongoc_structured_log_get_component_name.3
MONGOC_STRUCTURED_LOG_GET_COMPONENTlNAME(3)cRUCTURED_LOG_GET_COMPONENT_NAME(3)
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
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025UCTURED_LOG_GET_COMPONENT_NAME(3)
mongoc_structured_log_get_level_name.3
MONGOC_STRUCTURED_LOG_GET_LEVEL_NAME(3)ongocC_STRUCTURED_LOG_GET_LEVEL_NAME(3)
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, returns a pointer to a constant string that
should not be freed. If the level has no known name, returns NULL.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_STRUCTURED_LOG_GET_LEVEL_NAME(3)
mongoc_structured_log_get_named_component.3
MONGOC_STRUCTURED_LOG_GET_NAMED_COMPONENT(3)UCTURED_LOG_GET_NAMED_COMPONENT(3)
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.
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, returns true and writes the component
enum to *out. If the component name is not known, returns false and
does not write *out.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025CTURED_LOG_GET_NAMED_COMPONENT(3)
mongoc_structured_log_get_named_level.3
MONGOC_STRUCTURED_LOG_GET_NAMED_LEVEL(3)ngoc_STRUCTURED_LOG_GET_NAMED_LEVEL(3)
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.
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, returns true and writes the level enum to
*out. If the level name is not known, returns false and does not write
*out.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025STRUCTURED_LOG_GET_NAMED_LEVEL(3)
mongoc_structured_log_level_t.3
MONGOC_STRUCTURED_LOG_LEVEL_T(3) libmongoc MONGOC_STRUCTURED_LOG_LEVEL_T(3)
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 the available log levels for
use with structured logging.
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, returns a pointer to a constant string that
should not be freed. If the level has no known name, 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.
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, returns true and writes the level enum to
*out. If the level name is not known, returns false and does not write
*out.
SEE ALSO:
Structured Logging
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STRUCTURED_LOG_LEVEL_T(3)
mongoc_structured_log_opts_destroy.3
MONGOC_STRUCTURED_LOG_OPTS_DESTROY(3)bmongocGOC_STRUCTURED_LOG_OPTS_DESTROY(3)
SYNOPSIS
void
mongoc_structured_log_opts_destroy (mongoc_structured_log_opts_t *opts);
PARAMETERS
+ opts: Pointer to a mongoc_structured_log_opts_t allocated with
mongoc_structured_log_opts_new(), or NULL.
DESCRIPTION
This function releases all resources associated with a
mongoc_structured_log_opts_t. Does nothing if opts is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_STRUCTURED_LOG_OPTS_DESTROY(3)
mongoc_structured_log_opts_get_max_document_length.3
MONGOC_STRUCTURED_LOG_OPTSOGETCMAXRDOCUMENTcLENGTH(3)ET_MAX_DOCUMENT_LENGTH(3)
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 set in opts, as a size_t.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_SMayC12,E2025G_OPTS_GET_MAX_DOCUMENT_LENGTH(3)
mongoc_structured_log_opts_get_max_level_for_component.3
MONGOC_STRUCTURED_LOGMOPTSCGETRMAXULEVELnFORPCOMPONENT(3)EVEL_FOR_COMPONENT(3)
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 a specific component, as a
mongoc_structured_log_level_t. This may 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
may be the default obtained from environment variables. If an invalid
or unknown component enum is given, returns the lowest log level.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_STRUCMayE12,O2025TS_GET_MAX_LEVEL_FOR_COMPONENT(3)
mongoc_structured_log_opts_new.3
MONGOC_STRUCTURED_LOG_OPTS_NEW(3) libmongoc MONGOC_STRUCTURED_LOG_OPTS_NEW(3)
SYNOPSIS
mongoc_structured_log_opts_t *
mongoc_structured_log_opts_new (void);
Creates a new mongoc_structured_log_opts_t, filled with defaults cap-
tured 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 warn-
ings 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 implementa-
tion-specific value near the maximum representable length. By de-
fault, the limit is 1000 bytes. This limit affects interior docu-
ments 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:
When a file path is given for MONGODB_LOG_PATH, each log instance
(one stand-alone client or pool) will separately open this file
for append. The results are operating system specific. On
UNIX-like platforms each instance's output will be interleaved, in
most cases without splitting individual log messages. Notably on
Windows the file will be opened in exclusive mode by the first in-
stance and subsequent instances will fail, falling back on the de-
fault of stderr. Applications that use multiple processes or mul-
tiple client pools will likely want to supply a log handler that
annotates each message with information about its originating log
instance.
+ MONGODB_LOG_COMMAND: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_COMMAND.
+ MONGODB_LOG_TOPOLOGY: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_TOPOLOGY.
+ MONGODB_LOG_SERVER_SELECTION: A log level name to set as the maximum
for MONGOC_STRUCTURED_LOG_COMPONENT_SERVER_SELECTION.
+ MONGODB_LOG_CONNECTION: A log level name to set as the maximum for
MONGOC_STRUCTURED_LOG_COMPONENT_CONNECTION.
+ MONGODB_LOG_ALL: A log level name applied to all components not oth-
erwise specified.
Note that log level names are always case insensitive. This is a full
list of recognized names, including allowed aliases:
+ emergency, off
+ alert
+ critical
+ error
+ warning, warn
+ notice
+ informational, info
+ debug
+ trace
RETURNS
A newly allocated mongoc_structured_log_opts_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_STRUCTURED_LOG_OPTS_NEW(3)
mongoc_structured_log_opts_set_handler.3
MONGOC_STRUCTURED_LOG_OPTS_SET_HANDLER(3)gocSTRUCTURED_LOG_OPTS_SET_HANDLER(3)
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 to be called to handle structured log messages, as a
mongoc_structured_log_func_t.
The callback is given a mongoc_structured_log_entry_t as a handle for
obtaining additional information about the log message. This entry
pointer is only valid during a callback, because it's a low cost refer-
ence to temporary data.
Structured log handlers must be thread-safe if they will be used with
mongoc_client_pool_t. Handlers must avoid unbounded recursion, prefer-
ably by avoiding the use of any libmongoc client or pool which uses the
same handler.
This function always replaces the default log handler from
mongoc_structured_log_opts_new(), if it was still set. If the log_func
is set to NULL, structured logging will be disabled.
PARAMETERS
+ opts: Structured log options, allocated with
mongoc_structured_log_opts_new().
+ log_func: The handler to install, a mongoc_structured_log_func_t, or
NULL to disable structured logging.
+ user_data: Optional user data, passed on to the handler.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025TRUCTURED_LOG_OPTS_SET_HANDLER(3)
mongoc_structured_log_opts_set_max_document_length.3
MONGOC_STRUCTURED_LOG_OPTSOSETCMAXRDOCUMENTcLENGTH(3)ET_MAX_DOCUMENT_LENGTH(3)
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 appear serialized in JSON
form as part of a structured log message.
Serialized JSON will be truncated at this limit, interpreted as a count
of UTF-8 encoded bytes. Truncation will be indicated with a ... suffix,
the length of which is not included in the max document length. If
truncation at the exact indicated length would split a valid UTF-8 se-
quence, we instead truncate the document earlier at the nearest bound-
ary between code points.
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 trunca-
tion. Values near or above INT_MAX will be rejected.
RETURNS
Returns true on success, or false if the supplied maximum length is too
large.
SEE ALSO:
Structured Logging
mongoc_structured_log_opts_set_max_document_length_from_env()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_SMayC12,E2025G_OPTS_SET_MAX_DOCUMENT_LENGTH(3)
mongoc_structured_log_opts_set_max_document_length_from_env.3
MONGOC_STRUCTUREDOLOGCOPTSUSETRMAXLDOCUMENTcLENGTH_FROMMENV(3)NGTH_FROM_ENV(3)
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 a description of the supported en-
vironment variable formats.
Parse errors may cause a warning message, delivered via unstructured
logging.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may call
mongoc_structured_log_opts_set_max_document_length_from_env() after
calling mongoc_structured_log_opts_set_max_document_length(). This
will process the environment a second time, allowing it to override
customized defaults.
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 de-
sign, these errors are by default non-fatal. When
mongoc_structured_log_opts_new() internally calls this function, it ig-
nores the return value.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_STRUCTUREDMayG12,T2025T_MAX_DOCUMENT_LENGTH_FROM_ENV(3)
mongoc_structured_log_opts_set_max_level_for_all_components.3
MONGOC_STRUCTUREDOLOGCOPTSUSETRMAXLLEVELnFOREALLACOMPONENTS(3)LL_COMPONENTS(3)
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 all per-component maximum log levels to the same value. Only log
messages at or below this severity level will be passed to
mongoc_structured_log_func_t. Effective even for logging components
not known at compile-time.
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 in-
correct.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_STRUCTUREDMayG12,T2025T_MAX_LEVEL_FOR_ALL_COMPONENTS(3)
mongoc_structured_log_opts_set_max_level_for_component.3
MONGOC_STRUCTURED_LOGMOPTSCSETRMAXULEVELnFORPCOMPONENT(3)EVEL_FOR_COMPONENT(3)
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 be-
low this severity level will be passed to mongoc_structured_log_func_t.
By default, each component's log level may come from environment vari-
ables. 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 to set 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 supplied parameters were in-
correct.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_STRUCMayE12,O2025TS_SET_MAX_LEVEL_FOR_COMPONENT(3)
mongoc_structured_log_opts_set_max_levels_from_env.3
MONGOC_STRUCTURED_LOG_OPTSOSETCMAXRLEVELSgFROM_ENV(3)ET_MAX_LEVELS_FROM_ENV(3)
SYNOPSIS
bool
mongoc_structured_log_opts_set_max_levels_from_env (mongoc_structured_log_opts_t *opts);
Sets any maximum log levels requested by environment variables: MON-
GODB_LOG_ALL for all components, followed by per-component log levels
MONGODB_LOG_COMMAND, MONGODB_LOG_CONNECTION, MONGODB_LOG_TOPOLOGY, and
MONGODB_LOG_SERVER_SELECTION.
Expects the value to be recognizable by
mongoc_structured_log_get_named_level(). Parse errors may cause a
warning message, delivered via unstructured logging.
Component levels with no valid environment variable setting will be
left unmodified.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may 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(). This
will process the environment a second time, allowing it to override
customized defaults.
RETURNS
Returns true on success. If warnings are encountered in the environ-
ment, returns false and may log additional information to the unstruc-
tured logging facility. Note that, by design, these errors are by de-
fault non-fatal. When mongoc_structured_log_opts_new() internally
calls this function, it ignores the return value.
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOC_SMayC12,E2025G_OPTS_SET_MAX_LEVELS_FROM_ENV(3)
mongoc_structured_log_opts_t.3
MONGOC_STRUCTURED_LOG_OPTS_T(3) libmongoc MONGOC_STRUCTURED_LOG_OPTS_T(3)
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 maxi-
mum 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().
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 cap-
tured 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 warn-
ings 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 implementa-
tion-specific value near the maximum representable length. By de-
fault, the limit is 1000 bytes. This limit affects interior docu-
ments 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:
When a file path is given for MONGODB_LOG_PATH, each log instance
(one stand-alone client or pool) will separately open this file
for append. The results are operating system specific. On
UNIX-like platforms each instance's output will be interleaved, in
most cases without splitting individual log messages. Notably on
Windows the file will be opened in exclusive mode by the first in-
stance and subsequent instances will fail, falling back on the de-
fault of stderr. Applications that use multiple processes or mul-
tiple client pools will likely want to supply a log handler that
annotates each message with information about its originating log
instance.
+ MONGODB_LOG_COMMAND: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_COMMAND.
+ MONGODB_LOG_TOPOLOGY: A log level name to set as the maximum for MON-
GOC_STRUCTURED_LOG_COMPONENT_TOPOLOGY.
+ MONGODB_LOG_SERVER_SELECTION: A log level name to set as the maximum
for MONGOC_STRUCTURED_LOG_COMPONENT_SERVER_SELECTION.
+ MONGODB_LOG_CONNECTION: A log level name to set as the maximum for
MONGOC_STRUCTURED_LOG_COMPONENT_CONNECTION.
+ MONGODB_LOG_ALL: A log level name applied to all components not oth-
erwise specified.
Note that log level names are always case insensitive. This is a full
list of recognized names, including allowed aliases:
+ 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 allocated with
mongoc_structured_log_opts_new(), or NULL.
Description
This function releases all resources associated with a
mongoc_structured_log_opts_t. Does nothing if opts is NULL.
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 to be called to handle structured log messages, as a
mongoc_structured_log_func_t.
The callback is given a mongoc_structured_log_entry_t as a handle for
obtaining additional information about the log message. This entry
pointer is only valid during a callback, because it's a low cost refer-
ence to temporary data.
Structured log handlers must be thread-safe if they will be used with
mongoc_client_pool_t. Handlers must avoid unbounded recursion, prefer-
ably by avoiding the use of any libmongoc client or pool which uses the
same handler.
This function always replaces the default log handler from
mongoc_structured_log_opts_new(), if it was still set. If the log_func
is set to NULL, structured logging will be disabled.
Parameters
+ opts: Structured log options, allocated with
mongoc_structured_log_opts_new().
+ log_func: The handler to install, a mongoc_structured_log_func_t, or
NULL to disable structured logging.
+ user_data: Optional user data, passed on to the 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 be-
low this severity level will be passed to mongoc_structured_log_func_t.
By default, each component's log level may come from environment vari-
ables. 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 to set 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 supplied parameters were in-
correct.
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 all per-component maximum log levels to the same value. Only log
messages at or below this severity level will be passed to
mongoc_structured_log_func_t. Effective even for logging components
not known at compile-time.
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 in-
correct.
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 requested by environment variables: MON-
GODB_LOG_ALL for all components, followed by per-component log levels
MONGODB_LOG_COMMAND, MONGODB_LOG_CONNECTION, MONGODB_LOG_TOPOLOGY, and
MONGODB_LOG_SERVER_SELECTION.
Expects the value to be recognizable by
mongoc_structured_log_get_named_level(). Parse errors may cause a
warning message, delivered via unstructured logging.
Component levels with no valid environment variable setting will be
left unmodified.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may 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(). This
will process the environment a second time, allowing it to override
customized defaults.
Returns
Returns true on success. If warnings are encountered in the environ-
ment, returns false and may log additional information to the unstruc-
tured logging facility. Note that, by design, these errors are by de-
fault 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_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 a specific component, as a
mongoc_structured_log_level_t. This may 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
may be the default obtained from environment variables. If an invalid
or unknown component enum is given, returns the lowest log level.
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 appear serialized in JSON
form as part of a structured log message.
Serialized JSON will be truncated at this limit, interpreted as a count
of UTF-8 encoded bytes. Truncation will be indicated with a ... suffix,
the length of which is not included in the max document length. If
truncation at the exact indicated length would split a valid UTF-8 se-
quence, we instead truncate the document earlier at the nearest bound-
ary between code points.
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 trunca-
tion. Values near or above INT_MAX will be rejected.
Returns
Returns true on success, or false if the supplied maximum length 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 a description of the supported en-
vironment variable formats.
Parse errors may cause a warning message, delivered via unstructured
logging.
This happens automatically when mongoc_structured_log_opts_new() estab-
lishes 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, where
environment variables may override programmatic settings, they may call
mongoc_structured_log_opts_set_max_document_length_from_env() after
calling mongoc_structured_log_opts_set_max_document_length(). This
will process the environment a second time, allowing it to override
customized defaults.
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 de-
sign, these errors are by default non-fatal. When
mongoc_structured_log_opts_new() internally calls this function, it ig-
nores 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 set in opts, as a size_t.
SEE ALSO:
Structured Logging
SEE ALSO:
Structured Logging
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_STRUCTURED_LOG_OPTS_T(3)
mongoc_topology_description_destroy.3
MONGOC_TOPOLOGY_DESCRIPTION_DESTROY(3)mongocOC_TOPOLOGY_DESCRIPTION_DESTROY(3)
SYNOPSIS
void
mongoc_topology_description_destroy (mongoc_topology_description_t *description);
PARAMETERS
+ description: A mongoc_topology_description_t.
DESCRIPTION
Frees all resources associated with the topology description. Does
nothing if description is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_TOPOLOGY_DESCRIPTION_DESTROY(3)
mongoc_topology_description_get_servers.3
MONGOC_TOPOLOGY_DESCRIPTION_GET_SERVERS(3)ocOPOLOGY_DESCRIPTION_GET_SERVERS(3)
SYNOPSIS
mongoc_server_description_t **
mongoc_topology_description_get_servers (
const mongoc_topology_description_t *td,
size_t *n);
Fetches an array of mongoc_server_description_t structs for all known
servers in the topology.
PARAMETERS
+ td: A mongoc_topology_description_t.
+ n: Receives the length of the descriptions array.
RETURNS
A newly allocated array that must be freed with
mongoc_server_descriptions_destroy_all().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025POLOGY_DESCRIPTION_GET_SERVERS(3)
mongoc_topology_description_has_readable_server.3
MONGOC_TOPOLOGY_DESCRIPTION_HASGREADABLEnSERVER(3)PTION_HAS_READABLE_SERVER(3)
SYNOPSIS
bool
mongoc_topology_description_has_readable_server (
const mongoc_topology_description_t *td, const mongoc_read_prefs_t *prefs);
Determines if the topology has a readable server available. Servers are
filtered by the given read preferences only if the driver is connected
to a replica set, otherwise the read preferences are ignored. This
function uses the driver's current knowledge of the state of the Mon-
goDB server or servers it is connected to; it does no I/O and it does
not block.
PARAMETERS
+ td: A mongoc_topology_description_t.
+ read_prefs: A mongoc_read_prefs_t or NULL for default read prefer-
ences.
RETURNS
True if there is a known server matching prefs.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayO12,O2025ESCRIPTION_HAS_READABLE_SERVER(3)
mongoc_topology_description_has_writable_server.3
MONGOC_TOPOLOGY_DESCRIPTION_HASGWRITABLEnSERVER(3)PTION_HAS_WRITABLE_SERVER(3)
SYNOPSIS
bool
mongoc_topology_description_has_writable_server (
const mongoc_topology_description_t *td);
Determines if the topology has a writable server available, such as a
primary, mongos, or standalone. This function uses the driver's current
knowledge of the state of the MongoDB server or servers it is connected
to; it does no I/O and it does not block.
PARAMETERS
+ td: A mongoc_topology_description_t.
RETURNS
True if there is a known writable server.
SEE ALSO:
Introduction to Application Performance Monitoring
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGOMayO12,O2025ESCRIPTION_HAS_WRITABLE_SERVER(3)
mongoc_topology_description_new_copy.3
MONGOC_TOPOLOGY_DESCRIPTION_NEW_COPY(3)ongocC_TOPOLOGY_DESCRIPTION_NEW_COPY(3)
SYNOPSIS
mongoc_topology_description_t *
mongoc_topology_description_new_copy (
const mongoc_topology_description_t *description);
PARAMETERS
+ description: A mongoc_topology_description_t.
DESCRIPTION
Performs a deep copy of description.
RETURNS
Returns a newly allocated copy of description that should be freed with
mongoc_topology_description_destroy() when no longer in use. Returns
NULL if description is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_TOPOLOGY_DESCRIPTION_NEW_COPY(3)
mongoc_topology_description_t.3
MONGOC_TOPOLOGY_DESCRIPTION_T(3) libmongoc MONGOC_TOPOLOGY_DESCRIPTION_T(3)
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_de-
scription_t as a parameter to an SDAM Monitoring callback that must not
be destroyed. See Introduction to Application Performance Monitoring.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_TOPOLOGY_DESCRIPTION_T(3)
mongoc_topology_description_type.3
MONGOC_TOPOLOGY_DESCRIPTION_TYPE(3)libmongocONGOC_TOPOLOGY_DESCRIPTION_TYPE(3)
SYNOPSIS
const char *
mongoc_topology_description_type (const mongoc_topology_description_t *td);
PARAMETERS
+ td: A mongoc_topology_description_t.
DESCRIPTION
This function returns a string, one of the topology types defined in
the Server Discovery And Monitoring Spec:
+ Unknown
+ Single
+ Sharded
+ ReplicaSetNoPrimary
+ ReplicaSetWithPrimary
+ LoadBalanced
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_TOPOLOGY_DESCRIPTION_TYPE(3)
mongoc_transaction_opt_t.3
MONGOC_TRANSACTION_OPT_T(3) libmongoc MONGOC_TRANSACTION_OPT_T(3)
#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 trans-
action 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 <stdio.h>
#include <mongoc/mongoc.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) {
MONGOC_ERROR ("failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
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 {
MONGOC_ERROR ("Failed to create collection: %s", 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) {
MONGOC_ERROR ("Failed to start session: %s", 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)) {
MONGOC_ERROR ("Could not add session to opts: %s", error.message);
goto done;
}
retry_transaction:
r = mongoc_client_session_start_transaction (session, txn_opts, &error);
if (!r) {
MONGOC_ERROR ("Failed to start transaction: %s", 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) {
MONGOC_ERROR ("Insert failed: %s", 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 {
MONGOC_ERROR ("Warning: commit failed: %s", 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;
}
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_TRANSACTION_OPT_T(3)
mongoc_transaction_opts_clone.3
MONGOC_TRANSACTION_OPTS_CLONE(3) libmongoc MONGOC_TRANSACTION_OPTS_CLONE(3)
SYNOPSIS
mongoc_transaction_opt_t *
mongoc_transaction_opts_clone (const mongoc_transaction_opt_t *opts);
Create a copy of a transaction options struct.
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
RETURNS
A new mongoc_transaction_opt_t that must be freed with
mongoc_transaction_opts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_TRANSACTION_OPTS_CLONE(3)
mongoc_transaction_opts_destroy.3
MONGOC_TRANSACTION_OPTS_DESTROY(3) libmongocMONGOC_TRANSACTION_OPTS_DESTROY(3)
SYNOPSIS
void
mongoc_transaction_opts_destroy (mongoc_transaction_opt_t *opts);
Free a mongoc_transaction_opt_t. Does nothing if opts is NULL.
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_TRANSACTION_OPTS_DESTROY(3)
mongoc_transaction_opts_get_max_commit_time_ms.3
MONGOC_TRANSACTION_OPTS_GET_MAXNCOMMITmTIMEcMS(3)PTS_GET_MAX_COMMIT_TIME_MS(3)
SYNOPSIS
int64_t
mongoc_transaction_opts_get_max_commit_time_ms (const mongoc_transaction_opt_t *opts);
Return the transaction options' max commit time, in milliseconds. See
mongoc_transaction_opts_set_max_commit_time_ms().
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayT12,S2025ON_OPTS_GET_MAX_COMMIT_TIME_MS(3)
mongoc_transaction_opts_get_read_concern.3
MONGOC_TRANSACTION_OPTS_GET_READ_CONCERN(3)cANSACTION_OPTS_GET_READ_CONCERN(3)
SYNOPSIS
const mongoc_read_concern_t *
mongoc_transaction_opts_get_read_concern (const mongoc_transaction_opt_t *opts);
Return the transaction options' mongoc_read_concern_t. See
mongoc_transaction_opts_set_read_concern().
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
RETURNS
A mongoc_read_concern_t that is valid only for the lifetime of opts.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025NSACTION_OPTS_GET_READ_CONCERN(3)
mongoc_transaction_opts_get_read_prefs.3
MONGOC_TRANSACTION_OPTS_GET_READ_PREFS(3)gocTRANSACTION_OPTS_GET_READ_PREFS(3)
SYNOPSIS
const mongoc_read_prefs_t *
mongoc_transaction_opts_get_read_prefs (const mongoc_transaction_opt_t *opts);
Return the transaction options' mongoc_read_prefs_t. See
mongoc_transaction_opts_set_read_prefs().
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
RETURNS
A mongoc_read_prefs_t that is valid only for the lifetime of opts.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025RANSACTION_OPTS_GET_READ_PREFS(3)
mongoc_transaction_opts_get_write_concern.3
MONGOC_TRANSACTION_OPTS_GET_WRITE_CONCERN(3)NSACTION_OPTS_GET_WRITE_CONCERN(3)
SYNOPSIS
const mongoc_write_concern_t *
mongoc_transaction_opts_get_write_concern (const mongoc_transaction_opt_t *opts);
Return the transaction options' mongoc_write_concern_t. See
mongoc_transaction_opts_set_write_concern().
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
RETURNS
A mongoc_write_concern_t that is valid only for the lifetime of opts.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025SACTION_OPTS_GET_WRITE_CONCERN(3)
mongoc_transaction_opts_new.3
MONGOC_TRANSACTION_OPTS_NEW(3) libmongoc MONGOC_TRANSACTION_OPTS_NEW(3)
SYNOPSIS
mongoc_transaction_opt_t *
mongoc_transaction_opts_new (void);
Create a mongoc_transaction_opt_t to configure multi-document transac-
tions.
RETURNS
A new mongoc_transaction_opt_t that must be freed with
mongoc_transaction_opts_destroy().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_TRANSACTION_OPTS_NEW(3)
mongoc_transaction_opts_set_max_commit_time_ms.3
MONGOC_TRANSACTION_OPTS_SET_MAXNCOMMITmTIMEcMS(3)PTS_SET_MAX_COMMIT_TIME_MS(3)
SYNOPSIS
void
mongoc_transaction_opts_set_max_commit_time_ms (mongoc_transaction_opt_t *opts,
int64_t max_commit_time_ms);
Configure the transaction's max commit time, in milliseconds.
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
+ int64_t: Timeout for commitTransaction, in milliseconds.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MONGMayT12,S2025ON_OPTS_SET_MAX_COMMIT_TIME_MS(3)
mongoc_transaction_opts_set_read_concern.3
MONGOC_TRANSACTION_OPTS_SET_READ_CONCERN(3)cANSACTION_OPTS_SET_READ_CONCERN(3)
SYNOPSIS
void
mongoc_transaction_opts_set_read_concern (mongoc_transaction_opt_t *opts,
const mongoc_read_concern_t *read_concern);
Configure the transaction's read concern. The argument is copied into
the struct and can be freed after calling this function.
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
+ read_concern: A mongoc_read_concern_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayO12,C2025NSACTION_OPTS_SET_READ_CONCERN(3)
mongoc_transaction_opts_set_read_prefs.3
MONGOC_TRANSACTION_OPTS_SET_READ_PREFS(3)gocTRANSACTION_OPTS_SET_READ_PREFS(3)
SYNOPSIS
void
mongoc_transaction_opts_set_read_prefs (mongoc_transaction_opt_t *opts,
const mongoc_read_prefs_t *read_prefs);
Configure the transaction's read preference. The argument is copied
into the struct and can be freed after calling this function.
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
+ read_prefs: A mongoc_read_prefs_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,G2025RANSACTION_OPTS_SET_READ_PREFS(3)
mongoc_transaction_opts_set_write_concern.3
MONGOC_TRANSACTION_OPTS_SET_WRITE_CONCERN(3)NSACTION_OPTS_SET_WRITE_CONCERN(3)
SYNOPSIS
void
mongoc_transaction_opts_set_write_concern (mongoc_transaction_opt_t *opts,
const mongoc_write_concern_t *write_concern);
Configure the transaction's write concern. The argument is copied into
the struct and can be freed after calling this function.
PARAMETERS
+ opts: A mongoc_transaction_opt_t.
+ write_concern: A mongoc_write_concern_t.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayN12,_2025SACTION_OPTS_SET_WRITE_CONCERN(3)
mongoc_transaction_state_t.3
MONGOC_TRANSACTION_STATE_T(3) libmongoc MONGOC_TRANSACTION_STATE_T(3)
Constants for transaction states
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
These constants describe the current transaction state of a session.
FLAG VALUES
+---------------------------+----------------------------+
|MONGOC_TRANSACTION_NONE | There is no transaction in |
| | progress. |
+---------------------------+----------------------------+
|MONGOC_TRANSACTION_START- | A transaction has been |
|ING | started, but no operation |
| | has been sent to the |
| | server. |
+---------------------------+----------------------------+
|MONGOC_TRANSAC- | A transaction is in |
|TION_IN_PROGRESS | progress. |
+---------------------------+----------------------------+
|MONGOC_TRANSACTION_COMMIT- | The transaction was com- |
|TED | mitted. |
+---------------------------+----------------------------+
|MONGOC_TRANSACTION_ABORTED | The transaction was |
| | aborted. |
+---------------------------+----------------------------+
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_TRANSACTION_STATE_T(3)
mongoc_unstructured_log.3
MONGOC_UNSTRUCTURED_LOG(3) libmongoc MONGOC_UNSTRUCTURED_LOG(3)
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.
MACROS
To make logging a little less painful, various helper macros are pro-
vided. 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 std-
out, or to stderr for warnings, critical messages, and errors. You can
override the handler with mongoc_log_set_handler(). Your handler func-
tion 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_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 be-
fore 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 er-
rors, provide an empty log handler:
mongoc_log_set_handler (NULL, NULL);
TRACING
If compiling your own copy of the MongoDB C driver, consider configur-
ing with -DENABLE_TRACING=ON to enable function tracing and hex dumps
of network packets to STDERR and STDOUT during development and debug-
ging.
This is especially useful when debugging what may be going on inter-
nally in the driver.
Trace messages can be enabled and disabled by calling mon-
goc_log_trace_enable() and mongoc_log_trace_disable()
NOTE:
Compiling the driver with -DENABLE_TRACING=ON will affect its per-
formance. Disabling tracing with mongoc_log_trace_disable() signifi-
cantly reduces the overhead, but cannot remove it completely.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_UNSTRUCTURED_LOG(3)
mongoc_update_flags_t.3
MONGOC_UPDATE_FLAGS_T(3) libmongoc MONGOC_UPDATE_FLAGS_T(3)
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 bit-
wise or'd together. The allow for modifying the way an update is per-
formed 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 per- |
| | forming an update. This is |
| | useful if you already know |
| | your BSON documents are |
| | valid. |
+---------------------------+----------------------------+
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_UPDATE_FLAGS_T(3)
mongoc_uri_copy.3
MONGOC_URI_COPY(3) libmongoc MONGOC_URI_COPY(3)
SYNOPSIS
mongoc_uri_t *
mongoc_uri_copy (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Copies the entire contents of a URI.
RETURNS
A newly allocated mongoc_uri_t that should be freed with
mongoc_uri_destroy(). May return NULL on invalid host.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_COPY(3)
mongoc_uri_destroy.3
MONGOC_URI_DESTROY(3) libmongoc MONGOC_URI_DESTROY(3)
SYNOPSIS
void
mongoc_uri_destroy (mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Frees all resources associated with a uri. Does nothing if uri is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_DESTROY(3)
mongoc_uri_get_auth_mechanism.3
MONGOC_URI_GET_AUTH_MECHANISM(3) libmongoc MONGOC_URI_GET_AUTH_MECHANISM(3)
SYNOPSIS
const char *
mongoc_uri_get_auth_mechanism (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches the authMechanism parameter to an URI if provided.
RETURNS
A string which should not be modified or freed. Returns NULL if the au-
thMechanism parameter was not provided to uri.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_AUTH_MECHANISM(3)
mongoc_uri_get_auth_source.3
MONGOC_URI_GET_AUTH_SOURCE(3) libmongoc MONGOC_URI_GET_AUTH_SOURCE(3)
SYNOPSIS
const char *
mongoc_uri_get_auth_source (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches the authSource parameter of an URI if provided.
RETURNS
A string which should not be modified or freed if the authSource param-
eter is provided, otherwise NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_AUTH_SOURCE(3)
mongoc_uri_get_compressors.3
MONGOC_URI_GET_COMPRESSORS(3) libmongoc MONGOC_URI_GET_COMPRESSORS(3)
SYNOPSIS
const bson_t *
mongoc_uri_get_compressors (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Returns a bson document with the enabled compressors as the keys or an
empty document if no compressors were provided.
EXAMPLE
mongoc_client_t *client;
mongoc_uri_t *uri;
uri = mongoc_uri_new ("mongodb://localhost/?compressors=zlib,snappy,zstd");
if (bson_has_field (mongoc_uri_get_compressors (uri), "snappy")) {
/* snappy enabled */
}
RETURNS
A bson_t * which should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_COMPRESSORS(3)
mongoc_uri_get_database.3
MONGOC_URI_GET_DATABASE(3) libmongoc MONGOC_URI_GET_DATABASE(3)
SYNOPSIS
const char *
mongoc_uri_get_database (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches the database portion of an URI if provided. This is the portion
after the / but before the ?.
RETURNS
A string which should not be modified or freed or NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_DATABASE(3)
mongoc_uri_get_hosts.3
MONGOC_URI_GET_HOSTS(3) libmongoc MONGOC_URI_GET_HOSTS(3)
SYNOPSIS
const mongoc_host_list_t *
mongoc_uri_get_hosts (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches a linked list of hosts that were defined in the URI (the
comma-separated host section).
RETURNS
A linked list of mongoc_host_list_t structures that should not be modi-
fied or freed. Returns NULL if this URI's scheme is "mongodb+srv://".
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_HOSTS(3)
mongoc_uri_get_mechanism_properties.3
MONGOC_URI_GET_MECHANISM_PROPERTIES(3)mongocOC_URI_GET_MECHANISM_PROPERTIES(3)
SYNOPSIS
bool
mongoc_uri_get_mechanism_properties (const mongoc_uri_t *uri,
bson_t *properties /* OUT */);
PARAMETERS
+ uri: A mongoc_uri_t.
+ properties: An uninitialized bson_t.
DESCRIPTION
Fetches the "authMechanismProperties" options set on this mongoc_uri_t.
The out-parameter properties should be an uninitialized, stack-allo-
cated bson_t. It is statically initialized with bson_init_static() to
point to the internal data of uri, so its contents must not be modified
and it becomes invalid after uri is destroyed.
RETURNS
If no "authMechanismProperties" have been set on uri, this functions
returns false and properties remains uninitialized.
EXAMPLE
mongoc_uri_t *uri;
bson_t props;
uri = mongoc_uri_new (
"mongodb://user%40DOMAIN.COM:password@localhost/?authMechanism=GSSAPI"
"&authMechanismProperties=SERVICE_NAME:other,CANONICALIZE_HOST_NAME:true");
if (mongoc_uri_get_mechanism_properties (uri, &props)) {
char *json = bson_as_canonical_extended_json (&props, NULL);
printf ("%s\n", json);
bson_free (json);
} else {
printf ("No authMechanismProperties.\n");
}
This code produces the output:
{ "SERVICE_NAME" : "other", "CANONICALIZE_HOST_NAME" : "true" }
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_URI_GET_MECHANISM_PROPERTIES(3)
mongoc_uri_get_option_as_bool.3
MONGOC_URI_GET_OPTION_AS_BOOL(3) libmongoc MONGOC_URI_GET_OPTION_AS_BOOL(3)
SYNOPSIS
bool
mongoc_uri_get_option_as_bool (const mongoc_uri_t *uri,
const char *option,
bool fallback);
PARAMETERS
+ uri: A mongoc_uri_t.
+ option: The name of an option, case insensitive.
+ fallback: A default value to return.
DESCRIPTION
Returns the value of the URI option if it is set and of the correct
type (bool). If not set, or set to an invalid type, returns fallback.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_OPTION_AS_BOOL(3)
mongoc_uri_get_option_as_int32.3
MONGOC_URI_GET_OPTION_AS_INT32(3) libmongoc MONGOC_URI_GET_OPTION_AS_INT32(3)
SYNOPSIS
int32_t
mongoc_uri_get_option_as_int32 (const mongoc_uri_t *uri,
const char *option,
int32_t fallback);
PARAMETERS
+ uri: A mongoc_uri_t.
+ option: The name of an option, case insensitive.
+ fallback: A default value to return.
DESCRIPTION
Returns the value of the URI option if it is set and of the correct
type (integer). Returns fallback if the option is not set, set to an
invalid type, or zero.
Zero is considered "unset", so URIs can be constructed like so, and
still accept default values:
bson_strdup_printf ("mongodb://localhost/?connectTimeoutMS=%d", myvalue)
If myvalue is non-zero it is the connection timeout; if it is zero the
driver uses the default timeout.
When reading an option that is an int64, this function will return the
value as int32_t. If the value is outside the range of a 32-bit inte-
ger, a warning will be emitted and fallback is returned instead.
SEE ALSO:
mongoc_uri_get_option_as_int64()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_URI_GET_OPTION_AS_INT32(3)
mongoc_uri_get_option_as_int64.3
MONGOC_URI_GET_OPTION_AS_INT64(3) libmongoc MONGOC_URI_GET_OPTION_AS_INT64(3)
SYNOPSIS
int64_t
mongoc_uri_get_option_as_int64 (const mongoc_uri_t *uri,
const char *option,
int64_t fallback);
PARAMETERS
+ uri: A mongoc_uri_t.
+ option: The name of an option, case insensitive.
+ fallback: A default value to return.
DESCRIPTION
Returns the value of the URI option if it is set and of the correct
type (integer). Returns fallback if the option is not set, set to an
invalid type, or zero.
Zero is considered "unset", so URIs can be constructed like so, and
still accept default values:
bson_strdup_printf ("mongodb://localhost/?wTimeoutMS=%" PRId64, myvalue)
If myvalue is non-zero it is the write concern timeout; if it is zero
the driver uses the default timeout.
SEE ALSO:
mongoc_uri_get_option_as_int32()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_URI_GET_OPTION_AS_INT64(3)
mongoc_uri_get_option_as_utf8.3
MONGOC_URI_GET_OPTION_AS_UTF8(3) libmongoc MONGOC_URI_GET_OPTION_AS_UTF8(3)
SYNOPSIS
const char *
mongoc_uri_get_option_as_utf8 (const mongoc_uri_t *uri,
const char *option,
const char *fallback);
PARAMETERS
+ uri: A mongoc_uri_t.
+ option: The name of an option, case insensitive.
+ fallback: A default value to return.
DESCRIPTION
Returns the value of the URI option if it is set and of the correct
type (string). This value is a pointer into the URI's internal buffer,
and is only valid until the URI is modified or freed. If the option is
not set, or set to an invalid type, returns fallback.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_OPTION_AS_UTF8(3)
mongoc_uri_get_options.3
MONGOC_URI_GET_OPTIONS(3) libmongoc MONGOC_URI_GET_OPTIONS(3)
SYNOPSIS
const bson_t *
mongoc_uri_get_options (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches a bson document containing all of the options provided after
the ? of a URI.
RETURNS
A bson_t which should not be modified or freed if uri has options pro-
vided, otherwise NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_OPTIONS(3)
mongoc_uri_get_password.3
MONGOC_URI_GET_PASSWORD(3) libmongoc MONGOC_URI_GET_PASSWORD(3)
SYNOPSIS
const char *
mongoc_uri_get_password (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches the password portion of an URI.
RETURNS
A string which should not be modified or freed if uri has a password
specified, otherwise NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_PASSWORD(3)
mongoc_uri_get_read_concern.3
MONGOC_URI_GET_READ_CONCERN(3) libmongoc MONGOC_URI_GET_READ_CONCERN(3)
SYNOPSIS
const mongoc_read_concern_t *
mongoc_uri_get_read_concern (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches a read concern that is owned by the URI instance. This read
concern is configured based on URI parameters.
RETURNS
Returns a mongoc_read_concern_t that should not be modified or freed if
a read concern is provided to uri, otherwise NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_READ_CONCERN(3)
mongoc_uri_get_read_prefs_t.3
MONGOC_URI_GET_READ_PREFS_T(3) libmongoc MONGOC_URI_GET_READ_PREFS_T(3)
SYNOPSIS
const mongoc_read_prefs_t *
mongoc_uri_get_read_prefs_t (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches a read preference that is owned by the URI instance. This read
preference concern is configured based on URI parameters.
RETURNS
Returns a mongoc_read_prefs_t that should not be modified or freed if
uri has read preferences, otherwise NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_READ_PREFS_T(3)
mongoc_uri_get_replica_set.3
MONGOC_URI_GET_REPLICA_SET(3) libmongoc MONGOC_URI_GET_REPLICA_SET(3)
SYNOPSIS
const char *
mongoc_uri_get_replica_set (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches the replicaSet parameter of an URI.
RETURNS
Returns a string which should not be modified or freed. Returns NULL if
the replicaSet parameter was not provided to uri.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_REPLICA_SET(3)
mongoc_uri_get_server_monitoring_mode.3
MONGOC_URI_GET_SERVER_MONITORING_MODE(3)ngoc_URI_GET_SERVER_MONITORING_MODE(3)
SYNOPSIS
const char *
mongoc_uri_get_server_monitoring_mode (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches the serverMonitoringMode parameter to an URI if provided.
RETURNS
A string which should not be modified or freed. Returns "auto" if the
serverMonitoringMode parameter was not provided to uri.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025URI_GET_SERVER_MONITORING_MODE(3)
mongoc_uri_get_srv_hostname.3
MONGOC_URI_GET_SRV_HOSTNAME(3) libmongoc MONGOC_URI_GET_SRV_HOSTNAME(3)
SYNOPSIS
const char *
mongoc_uri_get_srv_hostname (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Returns the SRV host and domain name of a MongoDB URI.
RETURNS
A string if this URI's scheme is "mongodb+srv://", or NULL if the
scheme is "mongodb://".
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_SRV_HOSTNAME(3)
mongoc_uri_get_srv_service_name.3
MONGOC_URI_GET_SRV_SERVICE_NAME(3) libmongocMONGOC_URI_GET_SRV_SERVICE_NAME(3)
SYNOPSIS
const char *
mongoc_uri_get_srv_service_name (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Returns the SRV service name of a MongoDB URI.
RETURNS
A string corresponding to the value of the srvServiceName URI option if
present. Otherwise, the default value "mongodb".
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_URI_GET_SRV_SERVICE_NAME(3)
mongoc_uri_get_string.3
MONGOC_URI_GET_STRING(3) libmongoc MONGOC_URI_GET_STRING(3)
SYNOPSIS
const char *
mongoc_uri_get_string (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches the URI as a string.
RETURNS
Returns a string which should not be modified or freed.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_STRING(3)
mongoc_uri_get_tls.3
MONGOC_URI_GET_TLS(3) libmongoc MONGOC_URI_GET_TLS(3)
SYNOPSIS
bool
mongoc_uri_get_tls (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches a boolean indicating if TLS was specified for use in the URI.
RETURNS
Returns a boolean, true indicating that TLS should be used. This re-
turns true if any TLS option is specified.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_TLS(3)
mongoc_uri_get_username.3
MONGOC_URI_GET_USERNAME(3) libmongoc MONGOC_URI_GET_USERNAME(3)
SYNOPSIS
const char *
mongoc_uri_get_username (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches the username portion of a URI.
RETURNS
Returns a string which should not be modified or freed if uri has a
username provided, otherwise NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_USERNAME(3)
mongoc_uri_get_write_concern.3
MONGOC_URI_GET_WRITE_CONCERN(3) libmongoc MONGOC_URI_GET_WRITE_CONCERN(3)
SYNOPSIS
const mongoc_write_concern_t *
mongoc_uri_get_write_concern (const mongoc_uri_t *uri);
PARAMETERS
+ uri: A mongoc_uri_t.
DESCRIPTION
Fetches a write concern that is owned by the URI instance. This write
concern is configured based on URI parameters.
RETURNS
Returns a mongoc_write_concern_t that should not be modified or freed
if uri has a write concern provided, otherwise NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_GET_WRITE_CONCERN(3)
mongoc_uri_has_option.3
MONGOC_URI_HAS_OPTION(3) libmongoc MONGOC_URI_HAS_OPTION(3)
SYNOPSIS
bool
mongoc_uri_has_option (const mongoc_uri_t *uri, const char *option);
PARAMETERS
+ uri: A mongoc_uri_t.
+ option: The name of an option, case insensitive.
DESCRIPTION
Returns true if the option was present in the initial MongoDB URI.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_HAS_OPTION(3)
mongoc_uri_new.3
MONGOC_URI_NEW(3) libmongoc MONGOC_URI_NEW(3)
SYNOPSIS
mongoc_uri_t *
mongoc_uri_new (const char *uri_string);
PARAMETERS
+ uri_string: A string containing a URI.
DESCRIPTION
Calls mongoc_uri_new_with_error().
RETURNS
A newly allocated mongoc_uri_t if successful. Otherwise NULL, using
MONGOC_WARNING on error.
WARNING:
Failure to handle the result of this function is a programming er-
ror.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_NEW(3)
mongoc_uri_new_for_host_port.3
MONGOC_URI_NEW_FOR_HOST_PORT(3) libmongoc MONGOC_URI_NEW_FOR_HOST_PORT(3)
SYNOPSIS
mongoc_uri_t *
mongoc_uri_new_for_host_port (const char *hostname, uint16_t port);
PARAMETERS
+ hostname: A string containing the hostname.
+ port: A uint16_t.
DESCRIPTION
Creates a new mongoc_uri_t based on the hostname and port provided.
RETURNS
Returns a newly allocated mongoc_uri_t that should be freed with
mongoc_uri_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_NEW_FOR_HOST_PORT(3)
mongoc_uri_new_with_error.3
MONGOC_URI_NEW_WITH_ERROR(3) libmongoc MONGOC_URI_NEW_WITH_ERROR(3)
SYNOPSIS
mongoc_uri_t *
mongoc_uri_new_with_error (const char *uri_string,
bson_error_t *error);
PARAMETERS
+ uri_string: A string containing a URI.
+ error: An optional location for a bson_error_t or NULL.
DESCRIPTION
Parses a string containing a MongoDB style URI connection string.
RETURNS
A newly allocated mongoc_uri_t if successful. Otherwise NULL populating
error with the error description.
WARNING:
Failure to handle the result of this function is a programming er-
ror.
EXAMPLES
Examples of some valid MongoDB connection strings can be seen below.
"mongodb://localhost/"
"mongodb://localhost/?replicaSet=myreplset"
"mongodb://myuser:mypass@localhost/"
"mongodb://kerberosuser%40EXAMPLE.COM@example.com/?authMechanism=GSS-
API"
"mongodb://[::1]:27017/"
"mongodb://10.0.0.1:27017,10.0.0.1:27018,[::1]:27019/?tls=true"
"mongodb://%2Ftmp%2Fmongodb-27017.sock"
"mongodb://user:pass@%2Ftmp%2Fmongodb-27017.sock"
"mongodb://localhost,[::1]/mydb?authSource=mydb"
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_NEW_WITH_ERROR(3)
mongoc_uri_option_is_bool.3
MONGOC_URI_OPTION_IS_BOOL(3) libmongoc MONGOC_URI_OPTION_IS_BOOL(3)
SYNOPSIS
bool
mongoc_uri_option_is_bool (const char *option);
PARAMETERS
+ option: The name of an option, case insensitive.
DESCRIPTION
Returns true if the option is a known MongoDB URI option of boolean
type. For example, "tls=false" is a valid MongoDB URI option, so mon-
goc_uri_option_is_bool ("tls") is true.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_OPTION_IS_BOOL(3)
mongoc_uri_option_is_int32.3
MONGOC_URI_OPTION_IS_INT32(3) libmongoc MONGOC_URI_OPTION_IS_INT32(3)
SYNOPSIS
bool
mongoc_uri_option_is_int32 (const char *option);
PARAMETERS
+ option: The name of an option, case insensitive.
DESCRIPTION
Returns true if the option is a known MongoDB URI option of integer
type. For example, "zlibCompressionLevel=5" is a valid integer MongoDB
URI option, so mongoc_uri_option_is_int32 ("zlibCompressionLevel") is
true. This will also return true for all 64-bit integer options.
SEE ALSO:
mongoc_uri_option_is_int64()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_OPTION_IS_INT32(3)
mongoc_uri_option_is_int64.3
MONGOC_URI_OPTION_IS_INT64(3) libmongoc MONGOC_URI_OPTION_IS_INT64(3)
SYNOPSIS
bool
mongoc_uri_option_is_int64 (const char *option);
PARAMETERS
+ option: The name of an option, case insensitive.
DESCRIPTION
Returns true if the option is a known MongoDB URI option of 64-bit in-
teger type. For example, "wTimeoutMS=100" is a valid 64-bit integer
MongoDB URI option, so mongoc_uri_option_is_int64 ("wTimeoutMS") is
true.
SEE ALSO:
mongoc_uri_option_is_int32()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_OPTION_IS_INT64(3)
mongoc_uri_option_is_utf8.3
MONGOC_URI_OPTION_IS_UTF8(3) libmongoc MONGOC_URI_OPTION_IS_UTF8(3)
SYNOPSIS
bool
mongoc_uri_option_is_utf8 (const char *option);
PARAMETERS
+ option: The name of an option, case insensitive.
DESCRIPTION
Returns true if the option is a known MongoDB URI option of string
type. For example, "replicaSet=my_rs" is a valid MongoDB URI option, so
mongoc_uri_option_is_utf8 ("replicaSet") is true.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_OPTION_IS_UTF8(3)
mongoc_uri_set_auth_mechanism.3
MONGOC_URI_SET_AUTH_MECHANISM(3) libmongoc MONGOC_URI_SET_AUTH_MECHANISM(3)
SYNOPSIS
bool
mongoc_uri_set_auth_mechanism (mongoc_uri_t *uri, const char *value);
PARAMETERS
+ uri: A mongoc_uri_t.
+ value: The new "authMechanism" value.
DESCRIPTION
Sets the "authMechanism" URI option, such as "SCRAM-SHA-1" or "GSSAPI",
after the URI has been parsed from a string.
Updates the option in-place if already set, otherwise appends it to the
URI's bson_t of options.
RETURNS
Returns false if the option cannot be set, for example if value is not
valid UTF-8.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_AUTH_MECHANISM(3)
mongoc_uri_set_auth_source.3
MONGOC_URI_SET_AUTH_SOURCE(3) libmongoc MONGOC_URI_SET_AUTH_SOURCE(3)
SYNOPSIS
bool
mongoc_uri_set_auth_source (mongoc_uri_t *uri, const char *value);
PARAMETERS
+ uri: A mongoc_uri_t.
+ value: The new "authSource" value.
DESCRIPTION
Sets the "authSource" URI option, after the URI has been parsed from a
string.
Updates the option in-place if already set, otherwise appends it to the
URI's bson_t of options.
RETURNS
Returns false if the option cannot be set, for example if value is not
valid UTF-8.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_AUTH_SOURCE(3)
mongoc_uri_set_compressors.3
MONGOC_URI_SET_COMPRESSORS(3) libmongoc MONGOC_URI_SET_COMPRESSORS(3)
SYNOPSIS
bool
mongoc_uri_set_compressors (mongoc_uri_t *uri, const char *compressors);
PARAMETERS
+ uri: A mongoc_uri_t.
+ compressors: A string consisting of one or more comma (,) separated
compressors (e.g. "snappy,zlib") or NULL. Passing NULL clears any ex-
isting compressors set on uri.
DESCRIPTION
Sets the URI's compressors, after the URI has been parsed from a
string. Will overwrite any previously set value.
EXAMPLE
mongoc_client_t *client;
mongoc_uri_t *uri;
uri = mongoc_uri_new ("mongodb://localhost/");
mongoc_uri_set_compressors (uri, "snappy,zlib,zstd");
mongoc_client_new_from_uri (uri);
/* Snappy & zlib & zstd compressors are enabled */
RETURNS
Returns false if the option cannot be set, for example if compressors
is not valid UTF-8. Logs a warning to stderr with the MONGOC_WARNING
macro if compressor is not available.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_COMPRESSORS(3)
mongoc_uri_set_database.3
MONGOC_URI_SET_DATABASE(3) libmongoc MONGOC_URI_SET_DATABASE(3)
SYNOPSIS
bool
mongoc_uri_set_database (mongoc_uri_t *uri, const char *database);
PARAMETERS
+ uri: A mongoc_uri_t.
+ database: The new database name.
DESCRIPTION
Sets the URI's database, after the URI has been parsed from a string.
The driver authenticates to this database if the connection string in-
cludes authentication credentials. This database is also the return
value of mongoc_client_get_default_database().
RETURNS
Returns false if the option cannot be set, for example if database is
not valid UTF-8.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_DATABASE(3)
mongoc_uri_set_mechanism_properties.3
MONGOC_URI_SET_MECHANISM_PROPERTIES(3)mongocOC_URI_SET_MECHANISM_PROPERTIES(3)
SYNOPSIS
bool
mongoc_uri_set_mechanism_properties (mongoc_uri_t *uri,
const bson_t *properties);
PARAMETERS
+ uri: A mongoc_uri_t.
+ properties: A bson_t .
DESCRIPTION
Replaces all the options in URI's "authMechanismProperties" after the
URI has been parsed from a string.
RETURNS
Returns false if the option cannot be set, for example if properties is
not valid BSON data.
EXAMPLE
mongoc_uri_t *uri;
bson_t props = BSON_INITIALIZER;
uri = mongoc_uri_new (
"mongodb://user%40DOMAIN.COM:password@localhost/?authMechanism=GSSAPI"
"&authMechanismProperties=SERVICE_NAME:other,CANONICALIZE_HOST_NAME:true");
/* replace all options: replace service name "other" with "my_service", unset
* "CANONICALIZE_HOST_NAME" and accept its default.
*/
BSON_APPEND_UTF8 (&props, "SERVICE_NAME", "my_service");
mongoc_uri_set_mechanism_properties (uri, &props);
bson_destroy (&props);
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_URI_SET_MECHANISM_PROPERTIES(3)
mongoc_uri_set_option_as_bool.3
MONGOC_URI_SET_OPTION_AS_BOOL(3) libmongoc MONGOC_URI_SET_OPTION_AS_BOOL(3)
SYNOPSIS
bool
mongoc_uri_set_option_as_bool (const mongoc_uri_t *uri,
const char *option,
bool value);
PARAMETERS
+ uri: A mongoc_uri_t.
+ option: The name of an option, case insensitive.
+ value: The new value.
DESCRIPTION
Sets an individual URI option, after the URI has been parsed from a
string.
Only known options of type bool can be set.
Updates the option in-place if already set, otherwise appends it to the
URI's bson_t of options.
RETURNS
True if successfully set (the named option is a known option of type
bool).
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_OPTION_AS_BOOL(3)
mongoc_uri_set_option_as_int32.3
MONGOC_URI_SET_OPTION_AS_INT32(3) libmongoc MONGOC_URI_SET_OPTION_AS_INT32(3)
SYNOPSIS
bool
mongoc_uri_set_option_as_int32 (const mongoc_uri_t *uri,
const char *option,
int32_t value);
PARAMETERS
+ uri: A mongoc_uri_t.
+ option: The name of an option, case insensitive.
+ value: The new value.
DESCRIPTION
Sets an individual URI option, after the URI has been parsed from a
string.
Only known options of type integer can be set. Some integer options,
such as minHeartbeatFrequencyMS, have additional constraints.
Updates the option in-place if already set, otherwise appends it to the
URI's bson_t of options.
RETURNS
True if successfully set (the named option is a known option of type
int32 or int64).
SEE ALSO:
mongoc_uri_set_option_as_int64()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_URI_SET_OPTION_AS_INT32(3)
mongoc_uri_set_option_as_int64.3
MONGOC_URI_SET_OPTION_AS_INT64(3) libmongoc MONGOC_URI_SET_OPTION_AS_INT64(3)
SYNOPSIS
bool
mongoc_uri_set_option_as_int64 (const mongoc_uri_t *uri,
const char *option,
int64_t value);
PARAMETERS
+ uri: A mongoc_uri_t.
+ option: The name of an option, case insensitive.
+ value: The new value.
DESCRIPTION
Sets an individual URI option, after the URI has been parsed from a
string.
Only known options of type int32 or int64 can be set. For 32-bit inte-
ger options, the function returns false when trying to set a 64-bit
value that exceeds the range of an int32_t. Values that fit into an
int32_t will be set correctly. In both cases, a warning will be emit-
ted.
Updates the option in-place if already set, otherwise appends it to the
URI's bson_t of options.
RETURNS
True if successfully set (the named option is a known option of type
int64).
SEE ALSO:
mongoc_uri_option_is_int64()
mongoc_uri_set_option_as_int32()
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025MONGOC_URI_SET_OPTION_AS_INT64(3)
mongoc_uri_set_option_as_utf8.3
MONGOC_URI_SET_OPTION_AS_UTF8(3) libmongoc MONGOC_URI_SET_OPTION_AS_UTF8(3)
SYNOPSIS
bool
mongoc_uri_set_option_as_utf8 (const mongoc_uri_t *uri,
const char *option,
utf8 value);
PARAMETERS
+ uri: A mongoc_uri_t.
+ option: The name of an option, case insensitive.
+ value: The new value.
DESCRIPTION
Sets an individual URI option, after the URI has been parsed from a
string.
Only known string-type options can be set.
Updates the option in-place if already set, otherwise appends it to the
URI's bson_t of options.
RETURNS
True if successfully set (the named option is a known option of string
type).
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_OPTION_AS_UTF8(3)
mongoc_uri_set_password.3
MONGOC_URI_SET_PASSWORD(3) libmongoc MONGOC_URI_SET_PASSWORD(3)
SYNOPSIS
bool
mongoc_uri_set_password (mongoc_uri_t *uri, const char *password);
PARAMETERS
+ uri: A mongoc_uri_t.
+ password: The new password.
DESCRIPTION
Sets the URI's password, after the URI has been parsed from a string.
The driver authenticates with this password if the username is also
set.
RETURNS
Returns false if the option cannot be set, for example if password is
not valid UTF-8.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_PASSWORD(3)
mongoc_uri_set_read_concern.3
MONGOC_URI_SET_READ_CONCERN(3) libmongoc MONGOC_URI_SET_READ_CONCERN(3)
SYNOPSIS
void
mongoc_uri_set_read_concern (mongoc_uri_t *uri,
const mongoc_read_concern_t *rc);
PARAMETERS
+ uri: A mongoc_uri_t.
+ rc: A mongoc_read_concern_t.
DESCRIPTION
Sets a MongoDB URI's read concern option, after the URI has been parsed
from a string.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_READ_CONCERN(3)
mongoc_uri_set_read_prefs_t.3
MONGOC_URI_SET_READ_PREFS_T(3) libmongoc MONGOC_URI_SET_READ_PREFS_T(3)
SYNOPSIS
void
mongoc_uri_set_read_prefs_t (mongoc_uri_t *uri,
const mongoc_read_prefs_t *prefs);
PARAMETERS
+ uri: A mongoc_uri_t.
+ rc: A mongoc_read_prefs_t.
DESCRIPTION
Sets a MongoDB URI's read preferences, after the URI has been parsed
from a string.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_READ_PREFS_T(3)
mongoc_uri_set_server_monitoring_mode.3
MONGOC_URI_SET_SERVER_MONITORING_MODE(3)ngoc_URI_SET_SERVER_MONITORING_MODE(3)
SYNOPSIS
bool
mongoc_uri_set_server_monitoring_mode (mongoc_uri_t *uri, const char *value);
PARAMETERS
+ uri: A mongoc_uri_t.
+ value: The new serverMonitoringMode value.
DESCRIPTION
Sets the serverMonitoringMode URI option to value after the URI has
been parsed from a string.
Updates the option in-place if already set, otherwise appends it to the
URI's bson_t of options.
RETURNS
Returns false if the value is not "auto", "poll", or "stream".
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,N2025URI_SET_SERVER_MONITORING_MODE(3)
mongoc_uri_set_username.3
MONGOC_URI_SET_USERNAME(3) libmongoc MONGOC_URI_SET_USERNAME(3)
SYNOPSIS
bool
mongoc_uri_set_username (mongoc_uri_t *uri, const char *username);
PARAMETERS
+ uri: A mongoc_uri_t.
+ username: The new username.
DESCRIPTION
Sets the URI's username, after the URI has been parsed from a string.
The driver authenticates with this username if the password is also
set.
RETURNS
Returns false if the option cannot be set, for example if username is
not valid UTF-8.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_USERNAME(3)
mongoc_uri_set_write_concern.3
MONGOC_URI_SET_WRITE_CONCERN(3) libmongoc MONGOC_URI_SET_WRITE_CONCERN(3)
SYNOPSIS
void
mongoc_uri_set_write_concern (mongoc_uri_t *uri,
const mongoc_write_concern_t *wc);
PARAMETERS
+ uri: A mongoc_uri_t.
+ rc: A mongoc_write_concern_t.
DESCRIPTION
Sets a MongoDB URI's write concern option, after the URI has been
parsed from a string.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_SET_WRITE_CONCERN(3)
mongoc_uri_t.3
MONGOC_URI_T(3) libmongoc MONGOC_URI_T(3)
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 au-
thorization information.
See Connection String URI Reference on the MongoDB website for more in-
formation.
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 "mon-
godb+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.
3. The only required part of the uri. This specifies either a host-
name, IPv4 address, IPv6 address enclosed in "[" and "]", 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 'ad-
min' database.
7. Connection specific options.
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.
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.
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 follow-
ing mongod hosts:
+ db1.example.com on port 27017
+ db2.example.com on port 2500
You would use a connection string that resembles the following.
mongodb://db1.example.com,db2.example.com:2500/?replicaSet=test
SRV EXAMPLE
If you have configured an SRV record with a name like "_mon-
godb._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 per-
forms a DNS SRV query to resolve the service name to one or more host-
names. 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.
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.
Set the environment variable MONGOC_EXPERIMENTAL_SRV_PREFER_TCP to pre-
fer 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 en-
vironment variable is currently experimental and subject to change.
IPV4 AND IPV6
If connecting to a hostname that has both IPv4 and IPv6 DNS records,
the behavior follows RFC-6555. A connection to the IPv6 address is at-
tempted first. If IPv6 fails, then a connection is attempted to the
IPv4 address. If the connection attempt to IPv6 does not complete
within 250ms, then IPv4 is tried in parallel. Whichever succeeds con-
nection 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 configura-
tion. That is, only create an A record if the mongod is only listening
on IPv4.
CONNECTION OPTIONS
+-------------------+------------------+------------------+-------------------------------------+
|Constant | Key | Default | Description |
+-------------------+------------------+------------------+-------------------------------------+
|MON- | retryreads | true | If "true" and |
|GOC_URI_RETRYREADS | | | 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_RETRY- | retrywrites | true if driver | If "true" and |
|WRITES | | built w/ TLS | 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 docu- |
| | | | ments, or |
| | | | deletes of sin- |
| | | | gle documents |
| | | | are retried. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_APPNAME | appname | Empty (no app- | The client ap- |
| | | name) | plication name. |
| | | | This value is |
| | | | used by MongoDB |
| | | | when it logs |
| | | | connection in- |
| | | | formation and |
| | | | profile informa- |
| | | | tion, such as |
| | | | slow queries. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_TLS | tls | Empty (not set, | {true|false}, |
| | | same as false) | indicating if |
| | | | TLS must be |
| | | | used. (See also |
| | | | mongoc_client_set_ssl_opts() |
| | | | and |
| | | | mongoc_client_pool_set_ssl_opts().) |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_COM- | compressors | Empty (no com- | Comma separated list of compres- |
|PRESSORS | | pressors) | sors, 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_CON- | connecttimeoutms | 10,000 ms (10 | This setting applies to new server |
|NECTTIMEOUTMS | | seconds) | connections. It is also used as the |
| | | | socket timeout for server discovery |
| | | | and monitoring operations. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_SOCKET- | sockettimeoutms | 300,000 ms (5 | The time in milliseconds to attempt |
|TIMEOUTMS | | minutes) | to send or receive on a socket be- |
| | | | fore the attempt times out. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_REPLI- | replicaset | Empty (no repli- | The name of the Replica Set that |
|CASET | | caset) | the driver should connect to. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_ZLIB- | zlibcompression- | -1 | When the MONGOC_URI_COMPRESSORS in- |
|COMPRESSIONLEVEL | level | | cludes "zlib" this options config- |
| | | | ures the zlib compression level, |
| | | | when the zlib compressor is used to |
| | | | compress client data. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_LOAD- | loadbalanced | false | If true, this indicates the driver |
|BALANCED | | | is connecting to a MongoDB cluster |
| | | | behind a load balancer. |
+-------------------+------------------+------------------+-------------------------------------+
|MONGOC_URI_SRVMAX- | srvmaxhosts | 0 | If zero, the number of hosts in DNS |
|HOSTS | | | results is unlimited. If greater |
| | | | than zero, the number of hosts in |
| | | | DNS results is limited to being |
| | | | less than or equal to the given |
| | | | value. |
+-------------------+------------------+------------------+-------------------------------------+
WARNING:
Setting any of the *timeoutMS options above to either 0 or a nega-
tive value is discouraged due to unspecified and inconsistent behav-
ior. The "default value" historically specified as a fallback for 0
or a negative value is NOT related to the default values for the
*timeoutMS options documented above. The meaning of a timeout of 0
or a negative value may vary depending on the operation being exe-
cuted, even when specified by the same URI option. To specify the
documented default value for a *timeoutMS option, use the MONGOC_DE-
FAULT_* constants defined in mongoc-client.h instead.
AUTHENTICATION OPTIONS
+--------------------+--------------------+--------------------------+
|Constant | Key | Description |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_AUTH- | authmechanism | Specifies the mech- |
|MECHANISM | | anism to use when |
| | | authenticating as |
| | | the provided user. |
| | | See Authentication |
| | | for supported val- |
| | | ues. |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_AUTH- | authmechanismprop- | Additional proper- |
|MECHANISMPROPERTIES | erties | ties for the speci- |
| | | fied mechanism us- |
| | | ing key-value pair |
| | | format, e.g. |
| | | key1:value1,key2:value2. |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_AUTH- | authsource | The name of the database |
|SOURCE | | to which authentication |
| | | commands are sent or |
| | | $external depending on |
| | | the specified mechanism. |
| | | Overrides the auth data- |
| | | base in the URI when ap- |
| | | plicable. |
+--------------------+--------------------+--------------------------+
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
+---------------+----------------------------+
|Key | Value |
+---------------+----------------------------+
|ENVIRONMENT | The name of a built-in |
| | OIDC provider integration. |
| | Must be one of ["azure", |
| | "gcp", "k8s"]. |
+---------------+----------------------------+
|TOKEN_RESOURCE | The URI of the target re- |
| | source. 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
+-----------------------+----------------------------+
|Key | Value |
+-----------------------+----------------------------+
|SERVICE_NAME | Optional. Defaults to |
| | "mongodb". |
+-----------------------+----------------------------+
|CANONICALIZE_HOST_NAME | Optional. Must be one of |
| | ["false", "true"]. "false" |
| | performs no canonicaliza- |
| | tion (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 authenti- |
| | cation 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
+------------------+----------------------------+
|Key | Value |
+------------------+----------------------------+
|AWS_SESSION_TOKEN | Optional. An AWS session |
| | token to use for authenti- |
| | cation with temporary cre- |
| | dentials. |
+------------------+----------------------------+
Deprecated Mechanism Property Options
The following options have been deprecated and may be removed from fu-
ture releases of libmongoc.
+----------------+----------------+------------------+----------------+
|Constant | Key | Deprecated For | Key |
+----------------+----------------+------------------+----------------+
|MON- | canonicalize- | MONGOC_URI_AUTH- | authmechanism- |
|GOC_URI_CANONI- | hostname | MECHANISMPROPER- | properties |
|CALIZEHOSTNAME | | TIES (CANONICAL- | |
| | | IZE_HOST_NAME) | |
+----------------+----------------+------------------+----------------+
|MONGOC_URI_GSS- | gssapiservice- | MONGOC_URI_AUTH- | authmechanism- |
|APISERVICENAME | name | MECHANISMPROPER- | properties |
| | | TIES (SER- | |
| | | VICE_NAME) | |
+----------------+----------------+------------------+----------------+
TLS OPTIONS
+--------------------+---------------------+---------------------+
|Constant | Key | Description |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLS | tls | {true|false}, indi- |
| | | cating if TLS must |
| | | be used. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSCER- | tlscertificatekey- | Path to PEM format- |
|TIFICATEKEYFILE | file | ted Private Key, |
| | | with its Public |
| | | Certificate con- |
| | | catenated at the |
| | | end. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSCER- | tlscertificatekey- | The password, if |
|TIFICATEKEY- | password | any, to use to un- |
|FILEPASSWORD | | lock encrypted Pri- |
| | | vate Key. |
+--------------------+---------------------+---------------------+
|MON- | tlscafile | One, or a bundle |
|GOC_URI_TLSCAFILE | | of, Certificate Au- |
| | | thorities whom |
| | | should be consid- |
| | | ered to be trusted. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSAL- | tlsallowinvalidcer- | Accept and ignore |
|LOWINVALIDCERTIFI- | tificates | certificate verifi- |
|CATES | | cation errors (e.g. |
| | | untrusted issuer, |
| | | expired, etc.) |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSAL- | tlsallowinvalid- | Ignore hostname |
|LOWINVALIDHOSTNAMES | hostnames | verification of the |
| | | certificate (e.g. |
| | | Man In The Middle, |
| | | using valid cer- |
| | | tificate, but is- |
| | | sued for another |
| | | hostname) |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSINSE- | tlsinsecure | {true|false}, indi- |
|CURE | | cating if insecure |
| | | TLS options should |
| | | be used. Currently |
| | | this implies MON- |
| | | GOC_URI_TLSALLOWIN- |
| | | VALIDCERTIFICATES |
| | | and MONGOC_URI_TL- |
| | | SALLOWINVALIDHOST- |
| | | NAMES. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSDIS- | tlsdisablecertifi- | {true|false}, indi- |
|ABLECERTIFICATERE- | caterevocationcheck | cates if revocation |
|VOCATIONCHECK | | checking (CRL / |
| | | OCSP) should be |
| | | disabled. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_TLSDIS- | tlsdisableocspend- | {true|false}, indi- |
|ABLEOCSPEND- | pointcheck | cates if OCSP re- |
|POINTCHECK | | sponder endpoints |
| | | should not be re- |
| | | quested 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 fu-
ture releases of libmongoc.
+----------------------+------------------+-------------------+------------------+
|Constant | Key | Deprecated For | Key |
+----------------------+------------------+-------------------+------------------+
|MONGOC_URI_SSL | ssl | MONGOC_URI_TLS | tls |
+----------------------+------------------+-------------------+------------------+
|MON- | sslclientcer- | MON- | tlscertifi- |
|GOC_URI_SSLCLIENTCER- | tificatekeyfile | GOC_URI_TLSCER- | catekeyfile |
|TIFICATEKEYFILE | | TIFICATEKEYFILE | |
+----------------------+------------------+-------------------+------------------+
|MON- | sslclientcer- | MON- | tlscertifi- |
|GOC_URI_SSLCLIENTCER- | tificatekeypass- | GOC_URI_TLSCER- | catekeypassword |
|TIFICATEKEYPASSWORD | word | TIFICATEKEY- | |
| | | FILEPASSWORD | |
+----------------------+------------------+-------------------+------------------+
|MONGOC_URI_SSLCER- | sslcertifi- | MON- | tlscafile |
|TIFICATEAUTHORITYFILE | cateauthority- | GOC_URI_TLSCAFILE | |
| | file | | |
+----------------------+------------------+-------------------+------------------+
|MONGOC_URI_SSLALLOW- | sslallowinvalid- | MONGOC_URI_TLSAL- | tlsallowinvalid- |
|INVALIDCERTIFICATES | certificates | LOWINVALIDCER- | certificates |
| | | TIFICATES | |
+----------------------+------------------+-------------------+------------------+
|MONGOC_URI_SSLALLOW- | sslallowinvalid- | MONGOC_URI_TLSAL- | tlsallowinvalid- |
|INVALIDHOSTNAMES | hostnames | LOWINVALIDHOST- | hostnames |
| | | NAMES | |
+----------------------+------------------+-------------------+------------------+
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 (de-
fault 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 in-
sert--the thread rescans all servers every half-second. In this situa-
tion 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 sin-
gle-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 try-
ing to find it, then succeeds or returns an error with domain MON-
GOC_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 serverSelec-
tionTryOnce is set "false".
+--------------------+---------------------+---------------------+
|Constant | Key | Description |
+--------------------+---------------------+---------------------+
|MONGOC_URI_HEART- | heartbeatfrequen- | The interval be- |
|BEATFREQUENCYMS | cyms | tween server moni- |
| | | toring checks. De- |
| | | faults to 10,000ms |
| | | (10 seconds) in |
| | | pooled |
| | | (multi-threaded) |
| | | mode, 60,000ms (60 |
| | | seconds) in |
| | | non-pooled mode |
| | | (single-threaded). |
+--------------------+---------------------+---------------------+
|MONGOC_URI_SERVERS- | serverselection- | A timeout in mil- |
|ELECTIONTIMEOUTMS | timeoutms | liseconds to block |
| | | for server selec- |
| | | tion before throw- |
| | | ing an exception. |
| | | The default is |
| | | 30,0000ms (30 sec- |
| | | onds). |
+--------------------+---------------------+---------------------+
|MONGOC_URI_SERVERS- | serverselectiontry- | If "true", the |
|ELECTIONTRYONCE | once | 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 serverSelec- |
| | | tionTimeoutMS mil- |
| | | liseconds (pausing |
| | | a half second be- |
| | | tween attempts). |
| | | The default for |
| | | serverSelectionTry- |
| | | Once is "false" for |
| | | pooled clients, |
| | | otherwise "true". |
| | | Pooled clients ig- |
| | | nore serverSelec- |
| | | tionTryOnce; they |
| | | signal the thread |
| | | to rescan the |
| | | topology every |
| | | half-second until |
| | | serverSelection- |
| | | TimeoutMS expires. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_SOCK- | socketcheckinter- | Only applies to |
|ETCHECKINTERVALMS | valms | single threaded |
| | | clients. If a |
| | | socket has not been |
| | | used within this |
| | | time, its connec- |
| | | tion is checked |
| | | with a quick |
| | | "hello" call before |
| | | it is used again. |
| | | Defaults to 5,000ms |
| | | (5 seconds). |
+--------------------+---------------------+---------------------+
|MONGOC_URI_DIRECT- | directconnection | If "true", the |
|CONNECTION | | driver connects to |
| | | a single server di- |
| | | rectly and will not |
| | | monitor additional |
| | | servers. If |
| | | "false", the driver |
| | | connects based on |
| | | the presence and |
| | | value of the repli- |
| | | caSet option. |
+--------------------+---------------------+---------------------+
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.
+--------------------+--------------------+--------------------------+
|Constant | Key | Description |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_MAXPOOL- | maxpoolsize | The maximum number |
|SIZE | | 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 an- |
| | | other thread pushes |
| | | a client. |
+--------------------+--------------------+--------------------------+
|MONGOC_URI_WAIT- | waitqueuetimeoutms | The maximum time to wait |
|QUEUETIMEOUTMS | | for a client to become |
| | | available from the pool. |
+--------------------+--------------------+--------------------------+
WRITE CONCERN OPTIONS
+-------------------+------------+---------------------+
|Constant | Key | Description |
+-------------------+------------+---------------------+
MONGOC_URI_W w Determines the
write concern
(guarantee). Valid
values:
+ 0 = The
driver
will not
acknowl-
edge write
operations
but will
pass or
handle any
network
and socket
errors
that it
receives
to the
client. If
you dis-
able write
concern
but enable
the get-
LastError
command's
w option,
w over-
rides the
w option.
+ 1 = Pro-
vides ba-
sic ac-
knowledge-
ment of
write op-
erations.
By speci-
fying 1,
you re-
quire that
a stand-
alone mon-
god in-
stance, or
the pri-
mary for
replica
sets, ac-
knowledge
all write
opera-
tions. For
drivers
released
after the
default
write con-
cern
change,
this is
the de-
fault
write con-
cern set-
ting.
+ majority =
For
replica
sets, if
you spec-
ify the
special
majority
value to w
option,
write op-
erations
will only
return
success-
fully af-
ter a ma-
jority of
the con-
figured
replica
set mem-
bers have
acknowl-
edged the
write op-
eration.
+ n = For
replica
sets, if
you spec-
ify a num-
ber n
greater
than 1,
operations
with this
write con-
cern re-
turn only
after n
members of
the set
have ac-
knowledged
the write.
If you set
n to a
number
that is
greater
than the
number of
available
set mem-
bers or
members
that hold
data, Mon-
goDB will
wait, po-
tentially
indefi-
nitely,
for these
members to
become
available.
+ tags = For
replica
sets, you
can spec-
ify a tag
set to re-
quire that
all mem-
bers of
the set
that have
these tags
configured
return
confirma-
tion of
the write
operation.
+-------------------+------------+---------------------+
|MONGOC_URI_WTIME- | wtimeoutms | The time in mil- |
|OUTMS | | liseconds to wait |
| | | for replication to |
| | | succeed, as speci- |
| | | fied in the w op- |
| | | tion, before timing |
| | | out. When wtime- |
| | | outMS is 0, write |
| | | operations will |
| | | never time out. |
+-------------------+------------+---------------------+
|MONGOC_URI_JOURNAL | journal | Controls whether |
| | | write operations |
| | | will wait until the |
| | | mongod acknowledges |
| | | the write opera- |
| | | tions and commits |
| | | the data to the on |
| | | disk journal. |
| | | |
| | | + true = |
| | | Enables |
| | | journal |
| | | commit ac- |
| | | knowledge- |
| | | ment write |
| | | concern. |
| | | Equivalent |
| | | to speci- |
| | | fying the |
| | | getLastEr- |
| | | ror com- |
| | | mand with |
| | | the j op- |
| | | tion en- |
| | | abled. |
| | | |
| | | + false = |
| | | Does not |
| | | require |
| | | that mon- |
| | | god commit |
| | | write op- |
| | | erations |
| | | to the |
| | | journal |
| | | before ac- |
| | | knowledg- |
| | | ing the |
| | | write op- |
| | | eration. |
| | | This is |
| | | the de- |
| | | fault op- |
| | | tion for |
| | | the jour- |
| | | nal param- |
| | | eter. |
+-------------------+------------+---------------------+
READ CONCERN OPTIONS
+--------------------+------------------+---------------------+
|Constant | Key | Description |
+--------------------+------------------+---------------------+
|MONGOC_URI_READCON- | readconcernlevel | The level of isola- |
|CERNLEVEL | | tion for read oper- |
| | | ations. If the |
| | | level is left un- |
| | | specified, 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.
+--------------------+---------------------+---------------------+
|Constant | Key | Description |
+--------------------+---------------------+---------------------+
|MONGOC_URI_READ- | readpreference | Specifies the |
|PREFERENCE | | replica set read |
| | | preference for this |
| | | connection. This |
| | | setting overrides |
| | | any secondaryOk |
| | | value. The read |
| | | preference values |
| | | are the following: |
| | | |
| | | + primary |
| | | (default) |
| | | |
| | | + prima- |
| | | ryPre- |
| | | ferred |
| | | |
| | | + secondary |
| | | |
| | | + sec- |
| | | ondaryPre- |
| | | ferred |
| | | |
| | | + nearest |
+--------------------+---------------------+---------------------+
|MONGOC_URI_READ- | readpreferencetags | A representation of |
|PREFERENCETAGS | | a tag set. See also |
| | | Tag Sets. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_LO- | localthresholdms | How far to distrib- |
|CALTHRESHOLDMS | | ute queries, beyond |
| | | the server with the |
| | | fastest round-trip |
| | | time. By default, |
| | | only servers within |
| | | 15ms of the fastest |
| | | round-trip time re- |
| | | ceive queries. |
+--------------------+---------------------+---------------------+
|MONGOC_URI_MAXSTAL- | maxstalenessseconds | The maximum repli- |
|ENESSSECONDS | | cation lag, in wall |
| | | clock time, that a |
| | | secondary can suf- |
| | | fer and still be |
| | | eligible. The |
| | | smallest allowed |
| | | value for maxStale- |
| | | nessSeconds is 90 |
| | | seconds. |
+--------------------+---------------------+---------------------+
NOTE:
When connecting to more than one mongos, libmongoc's localThresh-
oldMS 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.
LEGACY OPTIONS
For historical reasons, the following options are available. They
should however not be used.
+----------------+------+---------------------+
|Constant | Key | Description |
+----------------+------+---------------------+
|MONGOC_URI_SAFE | safe | {true|false} Same |
| | | as w={1|0} |
+----------------+------+---------------------+
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_T(3)
mongoc_uri_unescape.3
MONGOC_URI_UNESCAPE(3) libmongoc MONGOC_URI_UNESCAPE(3)
SYNOPSIS
char *
mongoc_uri_unescape (const char *escaped_string);
PARAMETERS
+ escaped_string: A utf8 encoded string.
DESCRIPTION
Unescapes an URI encoded string. For example, "%40" would become "@".
RETURNS
Returns a newly allocated string that should be freed with bson_free().
If escaped_string contains an invalid UTF-8 character or an invalid es-
cape sequence, returns NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_URI_UNESCAPE(3)
mongoc_version.3
MONGOC_VERSION(3) libmongoc MONGOC_VERSION(3)
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/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.
#if MONGOC_CHECK_VERSION(1, 1, 0)
static void
do_something (void)
{
}
#endif
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_VERSION(3)
mongoc_write_concern_append.3
MONGOC_WRITE_CONCERN_APPEND(3) libmongoc MONGOC_WRITE_CONCERN_APPEND(3)
SYNOPSIS
bool
mongoc_write_concern_append (mongoc_write_concern_t *write_concern,
bson_t *command);
PARAMETERS
+ write_concern: A pointer to a mongoc_write_concern_t.
+ command: A pointer to a bson_t.
DESCRIPTION
This function appends a write concern to command options. It is useful
for appending a write concern to command options before passing them to
mongoc_client_write_command_with_opts() or a related function that
takes an options document.
RETURNS
Returns true on success. If any arguments are invalid, returns false
and logs an error.
EXAMPLE
See the example code for mongoc_client_write_command_with_opts().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_APPEND(3)
mongoc_write_concern_copy.3
MONGOC_WRITE_CONCERN_COPY(3) libmongoc MONGOC_WRITE_CONCERN_COPY(3)
SYNOPSIS
mongoc_write_concern_t *
mongoc_write_concern_copy (const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Performs a deep copy of write_concern.
RETURNS
Returns a newly allocated copy of write_concern that should be freed
with mongoc_write_concern_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_COPY(3)
mongoc_write_concern_destroy.3
MONGOC_WRITE_CONCERN_DESTROY(3) libmongoc MONGOC_WRITE_CONCERN_DESTROY(3)
SYNOPSIS
void
mongoc_write_concern_destroy (mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Frees all resources associated with the write concern structure. Does
nothing if write_concern is NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_DESTROY(3)
mongoc_write_concern_get_journal.3
MONGOC_WRITE_CONCERN_GET_JOURNAL(3)libmongocONGOC_WRITE_CONCERN_GET_JOURNAL(3)
SYNOPSIS
bool
mongoc_write_concern_get_journal (const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Fetches if the write should be journaled before indicating success.
RETURNS
Returns true if the write should be journaled.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_WRITE_CONCERN_GET_JOURNAL(3)
mongoc_write_concern_get_w.3
MONGOC_WRITE_CONCERN_GET_W(3) libmongoc MONGOC_WRITE_CONCERN_GET_W(3)
SYNOPSIS
int32_t
mongoc_write_concern_get_w (const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Fetches the w parameter of the write concern.
RETURNS
Returns an integer containing the w value. If wmajority is set, this
would be MONGOC_WRITE_CONCERN_W_MAJORITY.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_GET_W(3)
mongoc_write_concern_get_wmajority.3
MONGOC_WRITE_CONCERN_GET_WMAJORITY(3)bmongocGOC_WRITE_CONCERN_GET_WMAJORITY(3)
SYNOPSIS
bool
mongoc_write_concern_get_wmajority (
const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Fetches if the write should be written to a majority of nodes before
indicating success.
RETURNS
Returns true if wmajority is set.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_WRITE_CONCERN_GET_WMAJORITY(3)
mongoc_write_concern_get_wtag.3
MONGOC_WRITE_CONCERN_GET_WTAG(3) libmongoc MONGOC_WRITE_CONCERN_GET_WTAG(3)
SYNOPSIS
const char *
mongoc_write_concern_get_wtag (const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
A string containing the wtag setting if it has been set. Otherwise re-
turns NULL.
RETURNS
Returns a string which should not be modified or freed, or NULL.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_GET_WTAG(3)
mongoc_write_concern_get_wtimeout.3
MONGOC_WRITE_CONCERN_GET_WTIMEOUT(3)ibmongocNGOC_WRITE_CONCERN_GET_WTIMEOUT(3)
SYNOPSIS
int32_t
mongoc_write_concern_get_wtimeout (const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Get the timeout in milliseconds that the server should wait before re-
turning with a write concern timeout.
A value of 0 indicates no write timeout.
RETURNS
Returns an 32-bit signed integer containing the timeout.
SEE ALSO:
mongoc_write_concern_set_wtimeout() and mongoc_write_concern_get_wtimeout_int64().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_WRITE_CONCERN_GET_WTIMEOUT(3)
mongoc_write_concern_get_wtimeout_int64.3
MONGOC_WRITE_CONCERN_GET_WTIMEOUT_INT64(3)ocRITE_CONCERN_GET_WTIMEOUT_INT64(3)
SYNOPSIS
int64_t
mongoc_write_concern_get_wtimeout_int64 (const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Get the timeout in milliseconds that the server should wait before re-
turning with a write concern timeout.
A value of 0 indicates no write timeout.
RETURNS
Returns a 64-bit signed integer containing the timeout.
SEE ALSO:
mongoc_write_concern_set_wtimeout_int64().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025ITE_CONCERN_GET_WTIMEOUT_INT64(3)
mongoc_write_concern_is_acknowledged.3
MONGOC_WRITE_CONCERN_IS_ACKNOWLEDGED(3)ongocC_WRITE_CONCERN_IS_ACKNOWLEDGED(3)
SYNOPSIS
bool
mongoc_write_concern_is_acknowledged (
const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Test if this is an acknowledged or unacknowledged write concern.
If write_concern is NULL, returns true. (In other words, writes are ac-
knowledged by default.)
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,O2025_WRITE_CONCERN_IS_ACKNOWLEDGED(3)
mongoc_write_concern_is_default.3
MONGOC_WRITE_CONCERN_IS_DEFAULT(3) libmongocMONGOC_WRITE_CONCERN_IS_DEFAULT(3)
SYNOPSIS
bool
mongoc_write_concern_is_default (mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A pointer to a mongoc_write_concern_t.
DESCRIPTION
Returns true if write_concern has not been modified from the default.
For example, if no "w" option is set in the MongoDB URI and you have
not called mongoc_client_set_write_concern(), then
mongoc_write_concern_is_default() is true for the write concern re-
turned by mongoc_client_get_write_concern().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025ONGOC_WRITE_CONCERN_IS_DEFAULT(3)
mongoc_write_concern_is_valid.3
MONGOC_WRITE_CONCERN_IS_VALID(3) libmongoc MONGOC_WRITE_CONCERN_IS_VALID(3)
SYNOPSIS
bool
mongoc_write_concern_is_valid (const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Test if this write concern uses an invalid combination of options.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_IS_VALID(3)
mongoc_write_concern_journal_is_set.3
MONGOC_WRITE_CONCERN_JOURNAL_IS_SET(3)mongocOC_WRITE_CONCERN_JOURNAL_IS_SET(3)
SYNOPSIS
bool
mongoc_write_concern_journal_is_set (
const mongoc_write_concern_t *write_concern);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
DESCRIPTION
Test whether this write concern's "journal" option was explicitly set
or uses the default setting.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12,M2025C_WRITE_CONCERN_JOURNAL_IS_SET(3)
mongoc_write_concern_new.3
MONGOC_WRITE_CONCERN_NEW(3) libmongoc MONGOC_WRITE_CONCERN_NEW(3)
SYNOPSIS
mongoc_write_concern_t *
mongoc_write_concern_new (void);
RETURNS
Creates a newly allocated write concern that can be configured based on
user preference. This should be freed with
mongoc_write_concern_destroy() when no longer in use.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_NEW(3)
mongoc_write_concern_set_journal.3
MONGOC_WRITE_CONCERN_SET_JOURNAL(3)libmongocONGOC_WRITE_CONCERN_SET_JOURNAL(3)
SYNOPSIS
void
mongoc_write_concern_set_journal (mongoc_write_concern_t *write_concern,
bool journal);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
+ journal: A boolean.
DESCRIPTION
Sets if the write must have been journaled before indicating success.
Beginning in version 1.9.0, this function can now alter the write con-
cern after it has been used in an operation. Previously, using the
struct with an operation would mark it as "frozen" and calling this
function would log a warning instead instead of altering the write con-
cern.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025NGOC_WRITE_CONCERN_SET_JOURNAL(3)
mongoc_write_concern_set_w.3
MONGOC_WRITE_CONCERN_SET_W(3) libmongoc MONGOC_WRITE_CONCERN_SET_W(3)
SYNOPSIS
void
mongoc_write_concern_set_w (mongoc_write_concern_t *write_concern, int32_t w);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
+ w: Use MONGOC_WRITE_CONCERN_W_DEFAULT, MONGOC_WRITE_CONCERN_W_UNAC-
KNOWLEDGED, MONGOC_WRITE_CONCERN_W_MAJORITY, or a positive integer.
DESCRIPTION
Sets the w value for the write concern. See mongoc_write_concern_t for
more information on this setting.
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 MONGOC_WRITE_CONCERN_W_UN-
ACKNOWLEDGED, the write does not participate in causal consistency,
even when executed with a mongoc_client_session_t.
Beginning in version 1.9.0, this function can now alter the write con-
cern after it has been used in an operation. Previously, using the
struct with an operation would mark it as "frozen" and calling this
function would log a warning instead instead of altering the write con-
cern.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_SET_W(3)
mongoc_write_concern_set_wmajority.3
MONGOC_WRITE_CONCERN_SET_WMAJORITY(3)bmongocGOC_WRITE_CONCERN_SET_WMAJORITY(3)
SYNOPSIS
void
mongoc_write_concern_set_wmajority (mongoc_write_concern_t *write_concern,
int32_t wtimeout_msec);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
+ wtimeout_msec: A positive int32_t or zero. If you need to set wtime-
out with an int64_t, use mongoc_write_concern_set_wtimeout_int64().
DESCRIPTION
Sets if the write must have been propagated to a majority of nodes be-
fore indicating write success.
The timeout specifies how long, in milliseconds, the server should wait
before indicating that the write has failed. This is not the same as a
socket timeout. A value of zero may be used to indicate no timeout.
Beginning in version 1.9.0, this function can now alter the write con-
cern after it has been used in an operation. Previously, using the
struct with an operation would mark it as "frozen" and calling this
function would log a warning instead instead of altering the write con-
cern.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025OC_WRITE_CONCERN_SET_WMAJORITY(3)
mongoc_write_concern_set_wtag.3
MONGOC_WRITE_CONCERN_SET_WTAG(3) libmongoc MONGOC_WRITE_CONCERN_SET_WTAG(3)
SYNOPSIS
void
mongoc_write_concern_set_wtag (mongoc_write_concern_t *write_concern,
const char *tag);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
+ tag: A string containing the write tag.
DESCRIPTION
Sets the write tag that must be satisfied for the write to indicate
success. Write tags are preset write concerns configured on your Mon-
goDB server. See mongoc_write_concern_t for more information on this
setting.
Beginning in version 1.9.0, this function can now alter the write con-
cern after it has been used in an operation. Previously, using the
struct with an operation would mark it as "frozen" and calling this
function would log a warning instead instead of altering the write con-
cern.
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_SET_WTAG(3)
mongoc_write_concern_set_wtimeout.3
MONGOC_WRITE_CONCERN_SET_WTIMEOUT(3)ibmongocNGOC_WRITE_CONCERN_SET_WTIMEOUT(3)
SYNOPSIS
void
mongoc_write_concern_set_wtimeout (mongoc_write_concern_t *write_concern,
int32_t wtimeout_msec);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
+ wtimeout_msec: A positive int32_t or zero.
DESCRIPTION
Set the timeout in milliseconds that the server should wait before re-
turning with a write concern timeout. This is not the same as a socket
timeout. A value of zero may be used to indicate no write concern time-
out.
Beginning in version 1.9.0, this function can now alter the write con-
cern after it has been used in an operation. Previously, using the
struct with an operation would mark it as "frozen" and calling this
function would log a warning instead instead of altering the write con-
cern.
SEE ALSO:
mongoc_write_concern_get_wtimeout() and mongoc_write_concern_set_wtimeout_int64().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025GOC_WRITE_CONCERN_SET_WTIMEOUT(3)
mongoc_write_concern_set_wtimeout_int64.3
MONGOC_WRITE_CONCERN_SET_WTIMEOUT_INT64(3)ocRITE_CONCERN_SET_WTIMEOUT_INT64(3)
SYNOPSIS
void
mongoc_write_concern_set_wtimeout_int64 (mongoc_write_concern_t *write_concern,
int64_t wtimeout_msec);
PARAMETERS
+ write_concern: A mongoc_write_concern_t.
+ wtimeout_msec: A positive int64_t or zero.
DESCRIPTION
Set the timeout in milliseconds that the server should wait before re-
turning with a write concern timeout. This is not the same as a socket
timeout. A value of zero may be used to indicate no write concern time-
out.
Beginning in version 1.9.0, this function can now alter the write con-
cern after it has been used in an operation. Previously, using the
struct with an operation would mark it as "frozen" and calling this
function would log a warning instead instead of altering the write con-
cern.
SEE ALSO:
mongoc_write_concern_get_wtimeout_int64().
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev MayM12,O2025ITE_CONCERN_SET_WTIMEOUT_INT64(3)
mongoc_write_concern_t.3
MONGOC_WRITE_CONCERN_T(3) libmongoc MONGOC_WRITE_CONCERN_T(3)
Write Concern abstraction
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.
You can specify a write concern on connection objects, database ob-
jects, 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 collec-
tion's write concern, and a write concern error or timeout in the re-
sponse is considered a failure.
Exceptions to this principle are the generic command functions:
+ mongoc_client_command_simple()
+ mongoc_database_command_simple()
+ mongoc_collection_command_simple()
These generic command functions do not automatically apply a write con-
cern, and they do not check the server response for a write concern er-
ror 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_DE- | By default, writes block |
|FAULT (1) | awaiting acknowledgement |
| | from MongoDB. Acknowledged |
| | write concern allows |
| | clients to catch network, |
| | duplicate key, and other |
| | errors. |
+---------------------------+----------------------------+
|MONGOC_WRITE_CONCERN_W_UN- | With this write concern, |
|ACKNOWLEDGED (0) | MongoDB does not acknowl- |
| | edge the receipt of write |
| | operation. Unacknowledged |
| | is similar to errors ig- |
| | nored; however, mongoc at- |
| | tempts to receive and han- |
| | dle network errors when |
| | possible. |
+---------------------------+----------------------------+
|MONGOC_WRITE_CONCERN_W_MA- | Block until a write has |
|JORITY (majority) | been propagated to a ma- |
| | jority of the nodes in the |
| | replica set. |
+---------------------------+----------------------------+
|n | Block until a write has |
| | been propagated to at |
| | least n nodes in the |
| | replica set. |
+---------------------------+----------------------------+
AUTHOR
MongoDB, Inc
COPYRIGHT
2009-present, MongoDB, Inc.
2.1.0-dev May 12, 2025 MONGOC_WRITE_CONCERN_T(3)