Overview
多键索引可提高对数组值字段的查询性能。您可以使用与单字段或复合索引相同的语法来定义多键索引。
样本数据
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.
创建多键索引
以下示例在cast字段上创建多键索引:
bson_error_t error;bson_t *keys = BCON_NEW("cast", 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("cast", BCON_UTF8("Viola Davis"));
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 手册中的多键索引指南。
API 文档
要学习;了解有关本指南中讨论的任何函数的更多信息,请参阅以下API文档: