对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

单字段索引

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.

要创建单字段索引,请调用 create_index() 方法并指定包含以下信息的文档:

  • 要在其上创建索引的字段。

  • 索引值的排序顺序。 使用 1 进行升序,或使用 -1 进行降序。

注意

默认的 _id_索引就是单字段索引的一个示例。创建新集合时,会在 _id字段上自动创建此索引。

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"];

要学习如何创建免费的MongoDB Atlas 集群并加载示例数据集,请参阅MongoDB 入门指南。

以下示例使用 create_index() 方法在 title字段上创建升序单字段索引:

auto index_specification = make_document(kvp("title", 1));
auto result = collection.create_index(index_specification.view());

在前面的代码示例中创建的索引涵盖了以下查询:

auto document = collection.find_one(make_document(kvp("title","Peter Pan")));
std::cout << bsoncxx::to_json(*document) << std::endl;

要查看演示如何管理索引的可运行示例,请参阅使用索引优化查询。

要学习;了解有关索引的更多信息,请参阅MongoDB Server手册中的以下资源:

要学习;了解有关本指南中讨论的方法的更多信息,请参阅以下API文档: