Overview
单字段索引是引用集合文档中单个字段的索引。 它们提高了单字段查询和排序性能,并支持TTL 索引,该索引会在一定时间后或在特定时钟时间自动从集合中删除文档。
创建单字段索引时,必须指定以下内容:
要在其上创建索引的字段。
索引值的排序顺序(升序或降序)。 指定
BCON_INT32(1)表示升序,BCON_INT32(-1)表示降序。
注意
_id_索引是单字段索引的一个示例。 创建新集合时,会在_id字段上自动创建此索引。
样本数据
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.
创建单字段索引
以下示例将对 title 字段按升序创建索引:
bson_error_t error; bson_t *keys = BCON_NEW("title", 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("title", "Batman"); 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" : ..., "title" : "Batman", ... }
更多信息
要学习;了解有关单字段索引的更多信息,请参阅MongoDB Server手册中的单字段索引。
API 文档
要学习;了解有关本指南中讨论的任何函数的更多信息,请参阅以下API文档: