I am using the new C++ driver to access MongoDB from my C++ program. 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,:
cursor[i] or similar... which of course doesn't work.
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.
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. Instead, you likely want to invoke mongocxx::collection::count
.
How can I get the Nth element out of a cursor ? 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. 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.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.