单字段索引
概述
单字段索引是集合文档中单个字段的索引。它们可以提高单字段查询和排序性能,并支持TTL索引,这些索引会在一定时间后或特定时间自动从集合中删除文档。
创建单字段索引时,您必须指定以下内容
创建索引的字段。
索引值的排序顺序(升序或降序)。指定
BCON_INT32 (1)
为升序,BCON_INT32 (-1)
为降序。
注意
索引字段_id
是一个单字段索引的例子。当创建新集合时,此索引会自动在_id
字段上创建。
示例数据
本指南中的示例使用来自Atlas样本数据集的sample_mflix
数据库中的movies
集合。有关如何创建免费MongoDB Atlas集群并加载样本数据集的说明,请参阅Atlas入门指南。
创建单字段索引
以下示例在 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 服务器手册中的 单字段索引。
API 文档
要了解本指南中讨论的任何函数,请参阅以下 API 文档