Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 282
AbstractDissonance Avatar asked Nov 01 '16 08:11

AbstractDissonance


People also ask

How fetch data is limited in MongoDB?

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.

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.


1 Answers

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.

like image 87
sergiuz Avatar answered Sep 19 '22 04:09

sergiuz