Limit Aggregation in MongoDB

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

When you perform any kind of aggregation operations in MongoDB, documents pass through what is known as the aggregation pipeline. The MongoDB aggregation pipeline is comprised of multiple stages. The documents that enter the pipeline are transformed during each stage; the results of a stage are then passed to the next stage. In this article, we’ll focus on the $limit stage. We’ll explain how to use limit aggregation in MongoDB and look at some examples to better understand the process.

Prerequisite

In order to get the most out of this tutorial, two key prerequisites should be in place:

  • You should have MongoDB installed and configured on your machine.
  • You should have some basic knowledge of MongoDB

What is MongoDB $Limit?

The $limit stage of the MongoDB aggregation pipeline is one of the easiest to understand: It simply limits the number of documents being passed to the next stage of the pipeline.

Shown below is the basic syntax for the $limit stage:

1
{ $limit: <positive_integer> }

Notice that the $limit stage accepts a positive integer. This value indicates the maximum number of documents to be processed. The $limit stage only has an impact on the number of documents that are passed to the next stage of the aggregation pipeline; it does not change the contents of those documents in any way.

Create Sample Data Set

Before we attempt any examples, let’s create a sample data set that we can use for demo purposes. You can use the command below to create the same collection in your own MongoDB database:

1
2
3
4
5
6
7
8
9
db.articles.insertMany([
    {_id:1,title: "corona virus", word_count: 570},
    {_id:2,title: "the market during the outbreak", word_count: 790},
    {_id:3,title: "Behind Bars", word_count: 600},
    {_id:4,title: "The Pandemic of 2020", word_count: 900},
    {_id:5,title: "Covid-19 after math", word_count: 750},
    {_id:6,title: "Wuhan, Lost in space" , word_count: 850},
    {_id:7,title: "2020 Preppers", word_count: 980},
]);

Our collection of documents should now look something like this:

1
2
3
4
5
6
7
{ "_id" : 1, "title" : "corona virus", "word_count" : 570 }
{ "_id" : 2, "title" : "the market during the outbreak", "word_count" : 790 }
{ "_id" : 3, "title" : "Behind Bars", "word_count" : 600 }
{ "_id" : 4, "title" : "The Pandemic of 2020", "word_count" : 900 }
{ "_id" : 5, "title" : "Covid-19 after math", "word_count" : 750 }
{ "_id" : 6, "title" : "Wuhan, Lost in space", "word_count" : 850 }
{ "_id" : 7, "title" : "2020 Preppers", "word_count" : 980 }

MongoDB $limit Example

In this section, we’ll perform a MongoDB $limit aggregation against the collection we just created.

To do this, we’ll use the following command:

1
2
3
db.articles.aggregate(
    { $limit : 5 }
);

The command shown above will find documents within the articles collection and process only five documents as specified.

The result will look like this:

1
2
3
4
5
{ "_id" : 1, "title" : "corona virus", "word_count" : 570 }
{ "_id" : 2, "title" : "the market during the outbreak", "word_count" : 790 }
{ "_id" : 3, "title" : "Behind Bars", "word_count" : 600 }
{ "_id" : 4, "title" : "The Pandemic of 2020", "word_count" : 900 }
{ "_id" : 5, "title" : "Covid-19 after math", "word_count" : 750 }

NOTE: The $limit stage only accepts positive integers, since the value is meant to represent the number of documents to be processed and passed to the next stage. If you supply an invalid value, MongoDB will return an error like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
2020-02-25T16:27:51.285+0800 E  QUERY    [js] uncaught exception: Error: command failed: {
        "ok" : 0,
        "errmsg" : "the limit must be positive",
        "code" : 15958,
        "codeName" : "Location15958"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:583:17
assert.commandWorked@src/mongo/shell/assert.js:673:16
DB.prototype._runAggregate@src/mongo/shell/db.js:266:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1012:12
@(shell):1:1

Conclusion

If you need to perform aggregation operations in MongoDB, it’s helpful to understand the different stages of the aggregation pipeline. In this article, we turned our attention to the $limit stage, explaining its role in the pipeline and providing examples of its use. After following along with our instructions and examples, you’ll be prepared to use the limit aggregation in MongoDB for your own databases operations.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.