Docs 菜单
Docs 主页
/ /

复合索引

复合索引保存对集合文档中多个字段的引用,从而提高查询和排序性能。使用 mongoc_collection_create_indexes_with_opts() 函数创建复合索引。

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

  • 要索引的字段。

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

The examples in this guide use the movies collection in the sample_mflix database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.

以下示例对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);
{ "_id" : ..., "genres" : [ "Crime", "Drama" ], "title" : "Traffic in Souls", "type" : "movie", ... }
{ "_id" : ..., "genres" : [ "Drama" ], "title" : "Laugh, Clown, Laugh", "type" : "movie", ... }
{ "_id" : ..., "genres" : [ "Drama", "Romance" ], "title" : "A Woman of Paris: A Drama of Fate", "type" : "movie", ... }
{ "_id" : ..., "genres" : [ "Drama", "Romance", "Thriller" ], "title" : "He Who Gets Slapped", "type" : "movie", ... }
{ "_id" : ..., "genres" : [ "Drama", "Romance" ], "title" : "Wild Oranges", "type" : "movie", ... }
...

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

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

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

后退

单字段索引

在此页面上