文档菜单
文档首页
/ / /
C 驱动器
/

检索数据

本页内容

  • 概述
  • 示例数据
  • 查找文档
  • 查找文档示例
  • 修改查找行为
  • 附加信息
  • API 文档

在本指南中,您可以了解如何使用C驱动程序通过使用读取操作从MongoDB集合中检索数据。您可以调用mongoc_collection_find_with_opts() 函数来检索匹配查询过滤器中指定的一组标准的文档。

本指南中的示例使用来自 sample_restaurants 数据库中的 restaurants 集合。Atlas 示例数据集。要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅Atlas 入门指南。

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()函数的行为。以下表格描述了用于修改查询的常用选项

选项
描述
collation
设置查询的排序规则选项。
comment
指定附加到查询的字符串。这可以帮助您在服务器日志和性能数据中跟踪和解释操作。有关查询注释的更多信息,请参阅MongoDB服务器手册中的$comment
hint
指定用于查询的索引。
limit
限制查询返回的文档数量。
maxTimeMS
设置此操作在服务器上的最大执行时间。
skip
设置要跳过的文档数量。
sort
定义应用于查询的排序标准。

以下示例使用 limitmaxTimeMS 选项将查询返回的文档数量限制为 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 服务器手册中的 find 方法 文档。

有关查询过滤器的更多信息,请参阅 指定查询。

要查看使用 C 驱动程序检索文档的可运行代码示例,请参阅 从 MongoDB 读取数据。

有关本指南中讨论的任何函数的更多信息,请参阅以下 API 文档

返回

指定查询