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?
In MongoDB, you can use the limit() method to specify a maximum number of documents for a cursor to return. When you query a collection using the db. collection. find() method, you can append limit() to specify the limit.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With