Databases and Collections
On this page
Overview
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.
Access a Database
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"];
Access a Collection
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.
Create a Collection
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.
Get a List of Collections
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.
Delete a Collection
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.
Configure Read and Write Operations
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:
Configure Database Settings
This example shows how to configure read settings for your database by using the following functions:
read_preference()
: Sets the read preference tok_secondary
read_concern()
: Sets the read concern tok_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);
Tip
To see a description of each read preference and read concern option, see the following API documentation:
Configure Collection Settings
This example shows how to specify your collection's read and write concern by using the following functions:
read_concern()
: Sets the read concern tok_local
write_concern()
: Sets the write concern tok_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:
Tag Sets
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());
Local Threshold
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.
API Documentation
To learn more about any of the functions discussed in this guide, see the following API documentation: