[英]How to use the cursor in the new C++ Mongo Driver
I am using the new C++ driver to access MongoDB from my C++ program. 我正在使用新的C ++驱动程序从我的C ++程序访问MongoDB。 Through the tutorial I am able to fetch an entire collection from the DB.
通过本教程,我可以从数据库中获取整个集合。 I am also able to specify filters so I only get a few.
我也可以指定过滤器,所以我只能得到一些。
But once I get the collection data into the program, there is only a single example available for inspecting the data: 但是,一旦我将集合数据导入程序,只有一个示例可用于检查数据:
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
I would like to know how to get the count of the collection I would also like to know how to get number "i" in the return data, ie,: 我想知道如何获取集合的计数我也想知道如何在返回数据中获得数字“i”,即:
cursor[i] or similar... which of course doesn't work. 光标[i]或类似的...当然不起作用。
Thanks for pointing out this oversight in our examples. 感谢您在我们的示例中指出这种疏忽。 If you would, please file a bug in the Documentation component at https://jira.mongodb.org/browse/CXX requesting that our examples include more detail on how to access data on the client.
如果您愿意,请在https://jira.mongodb.org/browse/CXX上的文档组件中提交一个错误,请求我们的示例包含有关如何在客户端上访问数据的更多详细信息。
You have two questions here, really: 你有两个问题,真的:
How can I get a count ? 我如何计算 ? The unhelpful answer is that you could probably write
std::distance(cursor.begin(), cursor.end())
, but you probably don't want to do that, as it would require pulling all of the data back from the server. 无用的答案是你可以编写
std::distance(cursor.begin(), cursor.end())
,但你可能不想这样做,因为它需要std::distance(cursor.begin(), cursor.end())
所有数据服务器。 Instead, you likely want to invoke mongocxx::collection::count
. 相反,您可能想要调用
mongocxx::collection::count
。
How can I get the Nth element out of a cursor ? 如何从游标中获取第N个元素 ? First, are you sure this is what you want?
首先,你确定这是你想要的吗? The obvious way would be to do
auto view = *std::next(cursor.begin(), N-1)
, but again, this probably isn't what you want for the reasons above, and also because the order is not necessarily specified. 显而易见的方法是执行
auto view = *std::next(cursor.begin(), N-1)
,但同样,由于上述原因,这可能不是你想要的,也因为订单不是必须指明。 Instead, have a look at mongocxx::options::find::sort
, mongocxx::options::find::limit
, and mongocxx:options::find::skip
, which should give you finer control over what data is returned via the cursor, and in what order. 相反,看一下
mongocxx::options::find::sort
, mongocxx::options::find::limit
和mongocxx:options::find::skip
,它可以让你更好地控制返回的数据通过光标,以什么顺序。
Many thanks, acm! 非常感谢,嗯! I filed the bug and I figured out how to do it.
我提交了错误,我想出了如何做到这一点。 To help others, let me post the two code examples here:
为了帮助其他人,让我在这里发布两个代码示例:
auto db = conn["db-name"];
int count = db["collection-name"].count( {} );
And 和
mongocxx::options::find opts;
opts.limit( 1 );
auto cursor = db["db-name"].find({ }, opts);
bsoncxx::document::view doc = *cursor.begin();
std::cout << bsoncxx::to_json(doc) << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.