从游标访问数据
概述
在本指南中,您将学习如何使用C驱动程序从游标访问数据。
游标是一种机制,可以在可迭代批次中返回读取操作的结果。由于游标在任何给定时间都只保存文档的子集,因此游标减少了内存消耗和驱动程序向服务器发送的请求数量。
C驱动程序在执行返回多个文档的读取操作时,会自动将这些文档以游标的形式返回。
示例数据
本指南中的示例使用来自sample_restaurants
数据库的restaurants
集合。Atlas示例数据集。要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅Atlas入门指南。
迭代访问游标内容
要迭代游标的内容,请使用while循环。以下示例通过迭代游标检索restaurants
集合中的所有文档,并逐个打印每个文档
const bson_t *doc; bson_t *filter = bson_new (); 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" : { "$oid" : "..." }, ... , "name" : "Golden Pavillion", "restaurant_id" : "40363920" } { "_id" : { "$oid" : "..." }, ... , "name" : "Morris Park Bake Shop", "restaurant_id" : "30075445" } { "_id" : { "$oid" : "..." }, ... , "name" : "Criminal Court Bldg Cafeteria", "restaurant_id" : "40364443" } { "_id" : { "$oid" : "..." }, ... , "name" : "7B Bar", "restaurant_id" : "40364518" } { "_id" : { "$oid" : "..." }, ... , "name" : "Nyac Main Dining Room", "restaurant_id" : "40364467" } ...
单独检索文档
通过调用 mongoc_cursor_next()
函数单独从游标检索文档。此函数遍历游标并将 bson
参数设置为游标中的下一个文档。
以下示例找到具有 name
值为 "Dunkin' Donuts"
的集合中的所有文档。然后通过调用 mongoc_cursor_next()
函数打印游标中的第一个文档。
const bson_t *doc; bson_t *filter = BCON_NEW ("name", BCON_UTF8 ("Dunkin' Donuts")); mongoc_cursor_t *results = mongoc_collection_find_with_opts (collection, filter, NULL, NULL); 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" : { "$oid" : "..." }, ... , "name" : "Dunkin' Donuts", "restaurant_id" : "40392410" }
关闭游标
要关闭游标并释放所有相关资源,请调用如下示例中的 mongoc_cursor_destroy()
函数
mongoc_cursor_destroy (cursor);
可 tail 游标
当在 capped collection 上进行查询时,你可以使用在客户端耗尽游标结果后仍然保持打开状态的 tailable cursor。要在一个 capped 集合上创建 tailable cursor,请在执行 find 操作时指定 tailable
和 awaitData
选项。
以下示例在一个 capped 集合上创建了一个 tailable cursor
collection = mongoc_client_get_collection (client, "<database>", "<capped collection>"); bson_t *filter = bson_new (); bson_t *opts = BCON_NEW ("tailable", BCON_BOOL (true), "awaitData", BCON_BOOL (true)); mongoc_cursor_t *tailable_cursor = mongoc_collection_find_with_opts(collection, filter, opts, NULL); // Perform operations with tailable cursor here mongoc_cursor_destroy (tailable_cursor); bson_destroy (filter); bson_destroy (opts);
有关可 tail 游标及其使用的更多信息,请参阅 MongoDB 服务器手册中的 可 tail 游标指南。
故障排除
"CursorNotFound cursor id not valid at server"
MongoDB 中的游标如果在服务器上长时间打开且没有任何操作,则可能在服务器上超时。这可能导致在尝试迭代游标时出现 CursorNotFound
异常。要解决这个问题,请打开一个新的游标。
API 文档
要了解本指南中讨论的任何函数的更多信息,请参阅以下 API 文档