$limit
The $limit operator in Amazon DocumentDB is used to restrict the number of documents returned by a query. It is similar to the MongoDB $limit operator, but there are some specific considerations when using it with Amazon DocumentDB.
In Amazon DocumentDB, the $limit operator is useful for pagination, where you want to retrieve a subset of the total matching documents. It allows you to control the number of documents returned in each response, improving performance and reducing the amount of data transferred over the network.
Parameters
-
limit: The maximum number of documents to return. This must be a non-negative integer value.
Example (MongoDB Shell)
The following example demonstrates how to use the $limit operator to return a maximum of one document that matches the given filter.
Create sample documents
db.test.insertMany([ { "_id": 1, "star_rating": 4, "comments": "apple is red" }, { "_id": 2, "star_rating": 5, "comments": "comfortable couch" }, { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" }, { "_id": 4, "star_rating": 5, "comments": "this is a great couch" }, { "_id": 5, "star_rating": 5, "comments": "interesting couch" } ]);
Query example
db.test.createIndex({ comments: "text" }); db.test.find({ $and: [ { star_rating: 5 }, { $text: { $search: "couch" } } ] }).limit(1);
Output
[ { _id: 2, star_rating: 5, comments: 'comfortable couch' } ]
Code examples
To view a code example for using the $limit command, choose the tab for the language that you want to use: