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
  • Configure Database Settings
  • Configure Collection Settings
  • Tag Sets
  • Local Threshold
  • API Documentation

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

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.

You can access a database by calling the database() function on a mongocxx::client object and passing the name of the database as an argument.

The following example accesses a database named "test_database":

auto db = client.database("test_database");

Alternatively, you can use the [] operator on a mongocxx::client as a shorthand for the database() function, as shown in the following code:

auto db = client["test_database"];

You can access a collection by calling the collection() function on a mongocxx::database object and passing the name of the collection as an argument.

The following example accesses a collection named "test_collection":

auto coll = database.collection("test_collection");

Alternatively, you can use the [] operator on a mongocxx::database as a shorthand for the collection() function, as shown in the following code:

auto coll = 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.

You can use the create_collection() function to explicitly create a collection in a MongoDB database.

The following example creates a collection called "example_collection":

auto coll = database.create_collection("example_collection");

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

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

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

auto cursor = database.list_collections();
for(auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
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 list_collection_names() function as shown in the following example:

auto list = database.list_collection_names();
for(auto&& name : list) {
std::cout << name << std::endl;
}
test_collection
example_collection

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

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

The following example deletes the "test_collection" collection:

auto coll = database["test_collection"];
coll.drop();

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 mongocxx::client object, and collections inherit them from the database. However, you can change these settings by using one of the following functions on your database or collection:

  • read_preference()

  • read_concern()

  • write_concern()

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

This example shows how to configure read settings for your database by using the following functions:

  • read_preference(): Sets the read preference to k_secondary

  • read_concern(): Sets the read concern to k_majority

auto db = client["test_database"];
mongocxx::read_preference rp;
rp.mode(mongocxx::read_preference::read_mode::k_secondary);
mongocxx::read_concern rc;
rc.acknowledge_level(mongocxx::read_concern::level::k_majority);
db.read_preference(rp);
db.read_concern(rc);

This example shows how to specify your collection's read and write concern by using the following functions:

  • read_concern(): Sets the read concern to k_local

  • write_concern(): Sets the write concern to k_acknowledged

auto coll = client["test_database"]["test_collection"];
mongocxx::read_concern rc;
rc.acknowledge_level(mongocxx::read_concern::level::k_local);
mongocxx::write_concern wc;
wc.acknowledge_level(mongocxx::write_concern::level::k_acknowledged);
coll.read_concern(rc);
coll.write_concern(wc);

Tip

To see a description of each read and write concern level, see the following API documentation:

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, create a mongocxx::read_preference object and call its tags() member function. Pass your preferred tags as an array argument to tags().

In the following code example, the tag set passed to the 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"):

auto tag_set_ny = make_document(kvp("dc", "ny"));
auto tag_set_sf = make_document(kvp("dc", "sf"));
mongocxx::read_preference rp;
rp.mode(mongocxx::read_preference::read_mode::k_secondary);
rp.tags(make_array(tag_set_ny, tag_set_sf).view());

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:

mongocxx::uri uri("mongodb://localhost:27017/?localThresholdMS=35");
mongocxx::client client(uri);

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

Transactions