Overview
在本指南中,您可以学习如何使用C驱动程序通过读取操作从MongoDB集合中查找和检索文档。您可以调用 mongoc_collection_find_with_opts() 函数来检索与查询筛选条件中指定的一组条件匹配的文档。
样本数据
The examples in this guide use the restaurants collection in the sample_restaurants 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.
查找文档
mongoc_collection_find_with_opts() 函数采用 查询筛选条件 并返回 集合 中的所有匹配 文档。查询筛选条件是一个文档,其中指定了驱动程序用于匹配集合中的文档的条件。
如需学习;了解有关查询筛选器的更多信息,请参阅“指定查询”指南。
查找文档示例
以下示例使用 mongoc_collection_find_with_opts() 函数查找其中 cuisine字段的值为 "Spanish" 的所有文档:
bson_t *filter = BCON_NEW("cuisine", BCON_UTF8("Spanish")); mongoc_cursor_t *results = mongoc_collection_find_with_opts(collection, filter, NULL, NULL);
上示例中的 mongoc_collection_find_with_opts() 操作会返回一个 mongoc_cursor_t *,您可以使用 mongoc_cursor_next() 函数和一个 while 循环来遍历它。 以下示例遍历并打印上一个查询中返回的结果:
const bson_t *doc; bson_error_t error; while (mongoc_cursor_next(results, &doc)) { char *str = bson_as_canonical_extended_json(doc, NULL); printf("%s\n", str); bson_free(str); } // Ensure we iterated through cursor without error if (mongoc_cursor_error(results, &error)) { fprintf(stderr, "Error getting results: %s\n", error.message); } mongoc_cursor_destroy(results); bson_destroy(filter);
{ "_id" : { "$oid" : "..." }, "name" : "Charle'S Corner Restaurant & Deli", "cuisine" : "Spanish", ... } { "_id" : { "$oid" : "..." }, "name" : "Real Madrid Restaurant", "cuisine" : "Spanish", ... } { "_id" : { "$oid" : "..." }, "name" : "Malaga Restaurant", "cuisine" : "Spanish", ... } { "_id" : { "$oid" : "..." }, "name" : "Cafe Espanol", "cuisine" : "Spanish", ... } { "_id" : { "$oid" : "..." }, "name" : "Cafe Riazor", "cuisine" : "Spanish", ... } ...
注意
查找所有文档
要查找集合中的所有文档,请将空过滤传递给 mongoc_collection_find_with_opts() 函数:
bson_t *empty_filter = bson_new(); mongoc_cursor_t *results = mongoc_collection_find_with_opts(collection, empty_filter, NULL, NULL); mongoc_cursor_destroy(results); bson_destroy(empty_filter);
修改查找行为
您可以通过传入包含要配置的选项的 bson_t 结构来修改 mongoc_collection_find_with_opts() 函数的行为。 下表描述了常用于修改查询的选项:
选项 | 说明 |
|---|---|
| 设置查询的排序规则选项。 |
| 指定要添加到查询的字符串。这有助于在服务器日志和配置文件数据中追踪和解释操作。要详细了解查询注释,请参阅 cursor.comment()MongoDB Server 手册中的页面。 |
| 指定用于查询的索引。 |
| 限制查询返回的文档数量。 |
| 设置此操作在服务器上的最长执行时间。 |
| 设置要跳过的文档数。 |
| 定义要应用查询的排序条件。 |
以下示例使用 limit 和 maxTimeMS 选项将查询返回的文档数限制为 10,并将操作的最长执行时间设立为 10000 毫秒:
bson_t *filter = BCON_NEW("cuisine", BCON_UTF8("Spanish")); bson_t *opts = BCON_NEW("limit", BCON_INT32(10), "maxTimeMS", BCON_INT32(10000)); mongoc_cursor_t *results = mongoc_collection_find_with_opts(collection, filter, opts, NULL); mongoc_cursor_destroy(results); bson_destroy(filter); bson_destroy(opts);
有关修改mongoc_collection_find_with_opts() 行为的选项的完整列表,请参阅MongoDB Server手册中的 find 方法文档。
更多信息
如需了解有关查询过滤器的更多信息,请参阅指定查询。
要查看使用C驱动程序检索文档的可运行代码示例,请参阅读取数据。
API 文档
要学习;了解有关本指南中讨论的任何函数的更多信息,请参阅以下API文档: