Single field indexes are indexes that hold a reference to a single field in a collection's documents. These indexes improve single field query and sort performance. They also support TTL Indexes that automatically remove documents from a collection after a certain amount of time or at a specified clock time.
To create a single field 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.
The default _id_
index is an example of a single field index. This index is automatically created on the _id
field when a new collection is created.
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.
The following example uses the create_index()
method to create an ascending single field index on the title
field:
auto index_specification = make_document(kvp("title", 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")));std::cout << bsoncxx::to_json(*document) << std::endl;
{ "_id" :..., "plot" : "Peter Pan enters the nursery of the Darling children...","genres" : [ "Adventure", "Fantasy", "Family" ], "runtime" : 105,...}
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:
To learn more about the methods discussed in this guide, see the following API documentation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4