Simple program to create and print out two records:
main.cpp
#include <bsoncxx/builder/stream/document.hpp> #include <bsoncxx/types.hpp> #include <bsoncxx/json.hpp> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/uri.hpp> #include <iostream> int main() { mongocxx::instance inst{}; mongocxx::client conn{ mongocxx::uri{} }; auto db = conn["testcursor"]; db["names"].drop(); bsoncxx::document::value document = bsoncxx::builder::stream::document{} << "name" << "George" << bsoncxx::builder::stream::finalize; db["names"].insert_one(std::move(document)); document = bsoncxx::builder::stream::document{} << "name" << "Mark" << bsoncxx::builder::stream::finalize; db["names"].insert_one(std::move(document)); auto cursor = db["names"].find({}); for (auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; } return 0; }
Output (as expected):
{ "_id" : { "$oid" : "57b8b1209853f297f00005c1" }, "name" : "George" } { "_id" : { "$oid" : "57b8b1209853f297f00005c2" }, "name" : "Mark" }
Now, if I insert into the code cursor.begin(); right after the find():
auto cursor = db["names"].find({}); cursor.begin(); for (auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; }
Then my output is (unexpectedly missing the "George" entry):
{ "_id" : { "$oid" : "57b8b1c99853f26e68007472" }, "name" : "Mark" }
My objective was to test if the cursor was empty (there is no .empty()) so I tried to use:
if ( cursor.begin() == cursor.end() ) but that seemingly advances the iterator?
- is duplicated by
-
CXX-1337 Tailable cursor don't resume
- Closed
- is related to
-
CDRIVER-1886 Expose mongoc_cursor_t 'sent' field
- Closed
- related to
-
CXX-1100 Having more than one iterator per cursor violates mongoc lifecycle constraints
- Closed