Overview
In this guide, you can learn how to use the C driver to run MongoDB Search queries on a collection. MongoDB Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. MongoDB Search indexes specify the behavior of the search and which fields to index.
样本数据
The example in this guide uses 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 Get Started guide.
运行MongoDB搜索查询
This section shows how to create an aggregation pipeline to run a MongoDB Search query on a collection. In your bson_t structure that represents your pipeline stages, add the $search stage to specify the search criteria. Then, call the mongoc_collection_aggregate() function and pass your pipeline as a parameter.
提示
如需了解更多关于聚合操作的信息,请参阅聚合指南。
Before running a MongoDB Search query, you must create a MongoDB Search index on your collection. To learn how to programmatically create a MongoDB Search index, see the Create a Search Index section of the MongoDB Search Indexes guide.
MongoDB搜索示例
此示例通过执行以下操作来运行MongoDB搜索查询:
创建一个
$search阶段,指示驱动程序查询title字段包含单词"Alabama"的文档创建一个
$project阶段,指示驱动程序在查询结果中包含title字段Passes the pipeline stages to the
mongoc_collection_aggregate()function and prints the results
const bson_t *doc; bson_t *pipeline = BCON_NEW("pipeline", "[", "{", "$search", "{", "index", BCON_UTF8("<index name>"), "text", "{", "query", BCON_UTF8("Alabama"), "path", BCON_UTF8("title"), "}", "}", "}", "{", "$project", "{", "title", BCON_INT32(1), "}", "}", "]"); mongoc_cursor_t *results = mongoc_collection_aggregate(collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); while (mongoc_cursor_next(results, &doc)) { char *str = bson_as_canonical_extended_json(doc, NULL); printf("%s\n", str); bson_free(str); } bson_destroy(pipeline); mongoc_cursor_destroy(results);
{ "_id" : { "$oid" : "..." }, "title" : "Alabama Moon" } { "_id" : { "$oid" : "..." }, "title" : "Sweet Home Alabama" } { "_id" : { "$oid" : "..." }, "title" : "Crazy in Alabama" }
更多信息
要学习;了解有关MongoDB Search 的更多信息,请参阅Atlas文档中的MongoDB Search。
API 文档
要学习;了解有关 mongoc_collection_aggregate() 函数的详情,请参阅API文档。