29

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?

1

2 Answers 2

45

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.

Sign up to request clarification or add additional context in comments.

2 Comments

See the MongoDB Realm documentation for more details on this: docs.mongodb.com/realm/mongodb/actions/collection.find
See this medium article for some advice on doing paginated queries with MongoDB: medium.com/swlh/mongodb-pagination-fast-consistent-ece2a97070f3
1
db.collection.find({desired_conditions}).limit(postive_int)

here you just need to replace positive_int with number of results you want returned

1 Comment

this is the same as the accepted answer, which is unnecessary

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.