How to count the documents returned from collection.find(filter) in mongocxx? cursor object does NOT have a .count() method

54 Views Asked by At

The following C++ code written using mongocxx returns a cursor.

bsoncxx::document::value filter = make_document(...some document...);
auto cursor {coll.find(filter.view())}; // coll is the collection object

How can I count the returned documents? Because cursor does NOT have a .count() method.

1

There are 1 best solutions below

0
SPM On

I also don't see a count/size method in the cursor class. It has begin/end iterators, so it's technically possible to call std::distance(begin, end), but that's going to be utterly slow (linear complexity since it's going to loop through all the elements until reaching end()) and it's going to exhaust the cursor (it will point to end() once executed). So not a good idea.

Wouldn't you be able to just use count_documents() using the same filter?

bsoncxx::document::value filter = make_document(...some document...);
std::cout << "Size: " << coll.count_documents(filter.view());