MongoDB - Limit the Results of a Query

Return only the number of documents you need with the limit() method.

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.

Example

First let's do a query without a limit (so we can see how many documents are returned):

Without a Limit

Result:

{ "_id" : ObjectId("5780fbf948ef8c6b3ffb0149"), "artistname" : "The Tea Party" }
{ "_id" : ObjectId("5781c9ac48ef8c6b3ffb014a"), "artistname" : "Jorn Lande" }
{ "_id" : 1, "artistname" : "AC/DC" }
{ "_id" : ObjectId("5781d7f248ef8c6b3ffb014d"), "artistname" : "The Kooks" }
{ "_id" : ObjectId("5781d7f248ef8c6b3ffb014e"), "artistname" : "Bastille" }
{ "_id" : ObjectId("5781d7f248ef8c6b3ffb014f"), "artistname" : "Gang of Four" }

With a Limit

OK, so let's limit the results to say, 3 documents:

Result:

{ "_id" : ObjectId("5780fbf948ef8c6b3ffb0149"), "artistname" : "The Tea Party" }
{ "_id" : ObjectId("5781c9ac48ef8c6b3ffb014a"), "artistname" : "Jorn Lande" }
{ "_id" : 1, "artistname" : "AC/DC" }

In our query, we're using the $exists operator to check for the existence of a field. In this case we exclude those artists that have an albums field in the document.

This could easily be switched around to { $exists: true } to include only those artists with an albums field.

Add the skip() Method

You can use the skip() method to skip to a document within the cursor. In other words, you can control where MongoDB begins returning the results.

Result:

{ "_id" : ObjectId("5781c9ac48ef8c6b3ffb014a"), "artistname" : "Jorn Lande" }
{ "_id" : 1, "artistname" : "AC/DC" }
{ "_id" : ObjectId("5781d7f248ef8c6b3ffb014d"), "artistname" : "The Kooks" }

So you can see that it skipped the first result, but still returned 3 documents.

Note that skip() can be used on any query (not just ones with limit()).

For example, the query at the top of this page returned 6 documents. If we add skip(3), we will end up with the last 3 documents:

Result:

{ "_id" : ObjectId("5781d7f248ef8c6b3ffb014d"), "artistname" : "The Kooks" }
{ "_id" : ObjectId("5781d7f248ef8c6b3ffb014e"), "artistname" : "Bastille" }
{ "_id" : ObjectId("5781d7f248ef8c6b3ffb014f"), "artistname" : "Gang of Four" }