Search code examples
mongodbmongo-cxx-driver

Is there a way to know whether .limit() actually removes any documents?


Using mongocxx driver (c++ project).

Working on a mongodb query to paginate some results from a query. I'm trying to return the first 10 results, while also informing whether or not there are more results to fetch with another query (using an offset) - so as to inform the recipient if there are more documents to fetch. The results are stored in a std::vector after the db find query.

Is there any elegant way to do this, preferably without returning all the result documents and then comparing the vector size to the specified page limit?

Current query (without specifics):

db.collection.find({"<some_field>" : <some value>}).limit(10);

This, however, will not inform whether or not any documents were removed, in the case that exactly 10 results were found.

Currently I'm simply returning the full vector of results and looping through it, breaking if the loop goes over 10 iterations (and setting a "more_items" bool to true).


Solution

  • You have 2 ways to do this:

    1. Count all documents found by query:
    db.collection.count({"<some_field>" : <some value>});
    

    And then if there is more documents than you need (10 in here) - you can set "more_items" bool to true


    1. Find and set limit to +1 (11 in here):
    db.collection.find({"<some_field>" : <some value>}).limit(11);
    

    That way you find 11 documents or less.
    If you find 11 documents - this indicates that you have more documents than 10 (actual limit). If you find less than 11 - then you don't have documents to reach actual limit.