复合索引
概述
复合索引在集合文档的多个字段中存储引用,从而提高查询和排序性能。使用mongoc_collection_create_indexes_with_opts()
函数创建复合索引。
创建复合索引时,必须指定以下组件
要索引的字段。
每个字段的排序顺序(升序或降序)。指定
BCON_INT32 (1)
表示升序,BCON_INT32 (-1)
表示降序。
示例数据
本指南中的示例使用来自Atlas 示例数据集的sample_mflix
数据库中的movies
集合。有关如何创建免费的 MongoDB Atlas 集群并加载示例数据集的说明,请参阅Atlas 入门指南。
创建复合索引
以下示例在type
和genres
字段上创建了一个复合索引,这两个字段都按升序索引
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服务器手册中的复合索引。
要了解使用复合索引的有效索引策略,请参阅MongoDB服务器手册中的ESR规则。
API文档
要了解本指南中讨论的任何方法,请参阅以下API文档