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

复合索引

Compound indexes hold references to multiple fields within a collection's documents, improving query and sort performance. Use the mongoc_collection_create_indexes_with_opts() function to create compound indexes.

创建复合索引时,必须指定以下组成部分:

  • 要索引的字段。

  • 每个字段的排序顺序(升序或降序)。 指定 BCON_INT32(1) 表示升序,BCON_INT32(-1) 表示降序。

本指南中的示例使用来自 Atlas 示例数据集sample_mflix 数据库中的 movies 集合。要学习如何创建免费的MongoDB Atlas 集群并加载示例数据集,请参阅MongoDB 入门指南

以下示例对typegenres字段创建复合索引,这两个字段均按升序编入索引:

bson_error_t error;
bson_t *keys = BCON_NEW("type", BCON_INT32(1), "genres", BCON_INT32(1));
mongoc_index_model_t *index_model = mongoc_index_model_new(keys, NULL);
if (mongoc_collection_create_indexes_with_opts(collection, &index_model, 1, NULL, NULL, &error)) {
printf("Successfully created index\n");
} else {
fprintf(stderr, "Failed to create index: %s", error.message);
}
bson_destroy(keys);
mongoc_index_model_destroy(index_model);

以下示例执行的查询使用了在前面的代码示例中创建的索引:

const bson_t *doc;
bson_t *filter = BCON_NEW("type", BCON_UTF8("movie"),
"genres", BCON_UTF8("Drama"));
mongoc_cursor_t *results =
mongoc_collection_find_with_opts(collection, filter, NULL, NULL);
while (mongoc_cursor_next(results, &doc)) {
char *str = bson_as_canonical_extended_json(doc, NULL);
printf("%s\n", str);
bson_free(str);
}
mongoc_cursor_destroy(results);
bson_destroy(filter);

要学习;了解有关复合索引的更多信息,请参阅MongoDB Server手册中的复合索引

要学习;了解使用复合索引的有效索引策略,请参阅MongoDB Server手册中的 ESR 规则

要进一步了解本指南所讨论的任何方法,请参阅以下 API 文档: