多键索引
概述
多键索引是针对数组值字段查询性能的改进索引。您可以使用与单个字段或复合索引相同的语法定义多键索引。
示例数据
本指南中的示例使用来自movies
集合的 sample_mflix
数据库,该数据库来自Atlas示例数据集。有关创建免费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服务器手册中的多键索引指南。
API文档
有关本指南中讨论的任何函数的更多信息,请参阅以下API文档