mongodbmongodb-query

MongoDB limit find results


How can I query a collection and limit the returned results. Suppose I have a DB of 500M documents but I only want to search and return the first 10 matches without having to search the whole collection(for performance reasons).

Ideally I could return the nth through mth results in O(m-n) time.

Any ideas if this is possible or how to do it?


Solution

  • You can do that by applying skip and limit:

    db.collection.find(<query>).limit(<number>).skip(<number>)
    

    You can read more about performance issues on Limit the Number of Query Results to Reduce Network Demand

    Edit:

    limit and skip can be interchanged, skip is always called first.