Multikey Indexes
Overview
多键索引可提高对数组值字段的查询性能。您可以使用与单字段或复合索引。
样本数据
本指南中的示例使用 Atlas示例数据集的sample_mflix
数据库中的 movies
集合。 要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。
创建多键索引
以下示例在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);
{ "_id" : ..., "cast" : [ "Kelsey Grammer", "Cary Elwes", "Viola Davis", "John C. McGinley" ], "title" : "The Pentagon Wars", ... } { "_id" : ..., "cast" : [ "George Clooney", "Natascha McElhone", "Viola Davis", "Jeremy Davies" ], "title" : "Solaris", ... } { "_id" : ..., "cast" : [ "Meryl Streep", "Philip Seymour Hoffman", "Amy Adams", "Viola Davis" ], "title" : "Doubt", ... } { "_id" : ..., "cast" : [ "Hugh Jackman", "Jake Gyllenhaal", "Viola Davis", "Maria Bello" ], "title" : "Prisoners", ... } { "_id" : ..., "cast" : [ "Emma Stone", "Viola Davis", "Bryce Dallas Howard", "Octavia Spencer" ], "title" : "The Help", ... } ...
多键索引在查询覆盖、索引绑定计算和排序行为方面的行为与其他索引不同。 要了解有关多键索引的更多信息,包括对其行为和限制的讨论,请参阅 MongoDB Server 手册中的多键索引指南。
API 文档
要学习;了解有关本指南中讨论的任何函数的更多信息,请参阅以下API文档: