Compound Indexes
Overview
Compound indexes are indexes that hold references to multiple fields within a collection's documents. These indexes improve multi-field query and sort performance.
To create a compound index, call the create_index()
method and specify a document containing the following information:
Fields on which to create the index.
Sort order for the indexed values. Use``1`` for ascending or
-1
for descending.
Sample Data
The examples in this guide use the movies
collection in the sample_mflix
database from the Atlas sample datasets. To access this collection
from your C++ application, instantiate a mongocxx::client
that connects to an Atlas cluster
and assign the following values to your db
and collection
variables:
auto db = client["sample_mflix"]; auto collection = db["movies"];
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.
Create Compound Index
The following example creates an ascending compound index on the title
and year
fields:
auto index_specification = make_document(kvp("title", 1), kvp("year", 1)); auto result = collection.create_index(index_specification.view());
The following query is covered by the index created in the preceding code example:
auto document = collection.find_one(make_document(kvp("title","Peter Pan"), kvp("year", 1924))); std::cout << bsoncxx::to_json(*document) << std::endl;
{ "_id" :..., "plot" : "Peter Pan enters the nursery of the Darling children...", ..., "year" : 1924, "imdb" : ..., "type", "movie",...}
Additional Information
To view runnable examples that demonstrate how to manage indexes, see Optimize Queries with Indexes.
To learn more about indexes, see the following resources in the MongoDB Server manual:
API Documentation
To learn more about the methods discussed in this guide, see the following API documentation: