How to Use Mongoose Limit with MongoDB 723

Introduction

Mongoose is often used with NodeJS and MongoDB. Mongoose is an Object Data Modeling library that is used to create an environment for data. It provides many functions to make it easy to work with data and MongoDB. While working with databases, data fetching is one of the most commonly used operations. Functions such as find and findOne are used along with the query and projection. It all depends upon the requirements.

There are documents in a collection. There can be hundreds of documents in a collection. We can always provide a query to the find method to filter the data. But what if we want only a limited number of documents in the result? Suppose there are one hundred documents in a collection and we need only the first 10. Then what can we do? We can use the limit function. The limit function allows us to limit the documents in the result. In this article, we will discuss how to use the limit function in mongoose.

Mongoose limit

Observe the following route.

router.route("/getDocuments").get(function(req, res) {
  detail.find(function(err, detailcollection) {
    if (err) {
      console.log(err);
    } else {
      res.json(detailcollection);
    }
  });
});

Whenever the URL with endpoint – ‘/getDocuments’ is used, this route will be called. In this route, we have a find method that performs the find operation on the details collection. Let’s see what happens when this route in called.

[
  {
    _id: "5d769055d7b54d6ff55aebdd",
    name: "John",
    age: 21,
    location: "New York"
  },
  {
    _id: "5d769062d7b54d6ff55aebde",
    name: "Sam",
    age: 24,
    location: "Texas"
  },
  {
    _id: "5d769069d7b54d6ff55aebdf",
    name: "Lisa",
    age: 28,
    location: "Texas"
  },
  {
    _id: "5d769076d7b54d6ff55aebe0",
    name: "Max",
    age: 22,
    location: "Chicago"
  },
  {
    _id: "5d769084d7b54d6ff55aebe1",
    name: "Ronn",
    age: 32,
    location: "Detroit"
  },
  {
    _id: "5d769091d7b54d6ff55aebe2",
    name: "Sunny",
    age: 35,
    location: "Texas"
  }
];

It returns an array of objects containing all the documents in the details collection. We will use the limit function to limit the documents.

Currently, there are six documents in the collection. Suppose we want only the first four documents. Let’s see how can we use the limit function in this case.

detail
  .find(function(err, detailcollection) {
    if (err) {
      console.log(err);
    } else {
      res.json(detailcollection);
    }
  })
  .limit(4);

Here we attached the limit function at the end of the find method. It takes a whole number as an argument. We passed 4 because we want the first four documents of the details collection. We are using the postman tool to verify the results.

Image from Gyazo

Yes, it returns only the first four documents.

We can also use the limit function when a query is given to the find method. Suppose we want only those documents where location is “Texas”. Let’s make those changes in our find function.

router.route("/getDocuments").get(function(req, res) {
  detail.find({ location: "Texas" }, function(err, detailcollection) {
    if (err) {
      console.log(err);
    } else {
      res.json(detailcollection);
    }
  });
});

We have removed the limit function and specified a query to the find method – {“location”: “Texas”}. Let’s see what is the result.

Image from Gyazo

There are three documents where the location is “Texas”. Suppose now we need only first two documents where the location is “Texas”. We can simply attach a limit function at the end and pass 2 as the argument.

router
  .route("/getDocuments")
  .get(function(req, res) {
    detail.find({ location: "Texas" }, function(err, detailcollection) {
      if (err) {
        console.log(err);
      } else {
        res.json(detailcollection);
      }
    });
  })
  .limit(2);

Image from Gyazo

This time, it only returns the first two documents where the location is “Texas”.

Conclusion

The limit function is useful when there are too many records in a collection. It can be effectively used with the find method to filter the result.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed Redis,
MongoDB & Elasticsearch

Get Started

OR

Try CockroachDB
in Beta

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.