Docs Menu
Docs Home
/ / /
C Driver

Databases and Collections

On this page

  • Overview
  • Access a Database
  • Access a Collection
  • Create a Collection
  • Get a List of Collections
  • Delete a Collection
  • Configure Read and Write Operations
  • Tag Sets
  • Local Threshold
  • API Documentation

In this guide, you can learn how to interact with MongoDB databases and collections by using the C driver.

MongoDB organizes data into a hierarchy of the following levels:

  • Databases: Top-level data structures in a MongoDB deployment that store collections.

  • Collections: Groups of MongoDB documents. They are analogous to tables in relational databases.

  • Documents: Units that store literal data such as string, numbers, dates, and other embedded documents. For more information about document field types and structure, see the Documents guide in the MongoDB Server manual.

Access a database by using the mongoc_client_get_database() function.

The following example accesses a database named "test_database":

mongoc_database_t *database = mongoc_client_get_database (client, "test_database");

Access a collection by using the mongoc_client_get_collection() or mongoc_database_get_collection() functions.

The following example accesses a collection named "test_collection" by using the mongoc_database_get_collection() function:

mongoc_collection_t *collection = mongoc_database_get_collection (database, "test_collection");

Tip

If the provided collection name does not already exist in the database, MongoDB implicitly creates the collection when you first insert data into it.

Use the mongoc_database_create_collection() function to explicitly create a collection in a MongoDB database.

The following example creates a collection called "example_collection":

mongoc_collection_t *new_collection = mongoc_database_create_collection (database, "example_collection", NULL, &error);

You can specify collection options, such as maximum size and document validation rules, by passing them inside a bson_t structure as the third parameter to the mongoc_database_create_collection() function. For a full list of optional parameters, see the create command documentation in the MongoDB Server manual.

You can query for a list of collections in a database by calling the mongoc_database_find_collections_with_opts() function. The function returns a cursor containing all collections in the database and their associated metadata.

The following example calls the mongoc_database_find_collections_with_opts() function and iterates over the cursor to print the results:

mongoc_cursor_t *cursor = mongoc_database_find_collections_with_opts (database, NULL);
const bson_t *doc;
while (mongoc_cursor_next (cursor, &doc))
{
char *str = bson_as_canonical_extended_json (doc, NULL);
printf ("Collection: %s\n", str);
bson_free (str);
}
Collection: { "name" : "test_collection", "type" : "collection", ...}
Collection: { "name" : "example_collection", "type" : "collection", ... }

To query for only the names of the collections in the database, call the mongoc_database_get_collection_names_with_opts() function as follows:

char **strv;
unsigned i;
if ((strv = mongoc_database_get_collection_names_with_opts (database, 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);
}
test_collection
example_collection

For more information about iterating over a cursor, see Access Data From a Cursor.

You can delete a collection from the database by using the mongoc_collection_drop() function.

The following example deletes the "test_collection" collection:

mongoc_collection_t *collection = mongoc_database_get_collection (database, "test_collection");
mongoc_collection_drop (collection, NULL);

Warning

Dropping a Collection Deletes All Data in the Collection

Dropping a collection from your database permanently deletes all documents and all indexes within that collection.

Drop a collection only if the data in it is no longer needed.

You can control how the driver routes read operations by setting a read preference. You can also control options for how the driver waits for acknowledgment of read and write operations on a replica set by setting a read concern and a write concern.

By default, databases inherit these settings from the mongoc_client_t instance, and collections inherit them from the database. However, you can change these settings on your database by using one of the following functions:

  • mongoc_database_set_read_prefs()

  • mongoc_database_set_read_concern()

  • mongoc_database_set_write_concern()

The following example shows how to change the read preference of a database by using the mongoc_database_set_read_prefs() function:

mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY_PREFERRED);
mongoc_database_set_read_prefs (database, read_prefs);

You can change the read and write settings on your collections by using one of the following functions:

  • mongoc_collection_set_read_prefs()

  • mongoc_collection_set_read_concern()

  • mongoc_collection_set_write_concern()

The following example shows how to change the read preference of a collection by using the mongoc_collection_set_read_prefs() function:

mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY_PREFERRED);
mongoc_collection_set_read_prefs(collection, read_prefs);

To learn more about the read and write settings, see the following guides in the MongoDB Server manual:

In the MongoDB Server, you can apply key-value tags to replica-set members according to any criteria you choose. You can then use those tags to target one or more members for a read operation.

By default, the C driver ignores tags when choosing a member to read from. To instruct the C driver to prefer certain tags, use the mongoc_read_prefs_set_tags() function to set the tags in an instance of mongoc_read_prefs_t.

In the following code example, the tag set passed to the mongoc_read_prefs_set_tags() function instructs the C driver to prefer reads from the New York data center ('dc': 'ny') and to fall back to the San Francisco data center ('dc': 'sf'):

mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY_PREFERRED);
bson_t *tags = BCON_NEW ("DC", BCON_UTF8("ny"), "DC", BCON_UTF8("sf"));

If multiple replica-set members match the read preference and tag sets you specify, the C driver reads from the nearest replica-set members, chosen according to their ping time.

By default, the driver uses only those members whose ping times are within 15 milliseconds of the nearest member for queries. To distribute reads between members with higher latencies, include the localThresholdMS parameter in your connection string URI.

The following example connects to a MongoDB deployment running on localhost:27017 and specifies a local threshold of 35 milliseconds:

const char *uri_string = "mongodb://localhost:27017/?localThresholdMS=35";
mongoc_client_t *client = mongoc_client_new (uri_string);

In the preceding example, the C driver distributes reads between matching members within 35 milliseconds of the closest member's ping time.

To learn more about any of the functions discussed in this guide, see the following API documentation:

Back

Configure TLS