How do I limit the number of returned items?

Mongoose

Mongoose Problem Overview


myModel.find({}, function(err, items) {
    console.log(items.length);    // Big number
});

How can I limit the returned items to only the latest 10 items that were inserted?

Mongoose Solutions


Solution 1 - Mongoose

In the latest mongoose (3.8.1 at the time of writing), you do two things differently: (1) you have to pass single argument to sort(), which must be an array of constraints or just one constraint, and (2) execFind() is gone, and replaced with exec() instead. Therefore, with the mongoose 3.8.1 you'd do this:

var q = models.Post.find({published: true}).sort({'date': -1}).limit(20);
q.exec(function(err, posts) {
     // `posts` will be of length 20
});

or you can chain it together simply like that:

models.Post
  .find({published: true})
  .sort({'date': -1})
  .limit(20)
  .exec(function(err, posts) {
       // `posts` will be of length 20
  });

Solution 2 - Mongoose

Like this, using .limit():

var q = models.Post.find({published: true}).sort('date', -1).limit(20);
q.execFind(function(err, posts) {
  // `posts` will be of length 20
});

Solution 3 - Mongoose

I am a bit lazy, so I like simple things:

let users = await Users.find({}, null, {limit: 50});

Solution 4 - Mongoose

models.Post.find({published: true}, {sort: {'date': -1}, limit: 20}, function(err, posts) {
 // `posts` with sorted length of 20
});

Solution 5 - Mongoose

Find parameters

The parameters find function takes are as follows:

  1. conditions «Object».
  2. [projection] «Object|String» optional fields to return, see Query.prototype.select()
  3. [options] «Object» optional see Query.prototype.setOptions()
  4. [callback] «Function»

How to limit

const Post = require('./models/Post');

Post.find(
  { published: true }, 
  null, 
  { sort: { 'date': 'asc' }, limit: 20 },
  function(error, posts) {
   if (error) return `${error} while finding from post collection`;
   
   return posts; // posts with sorted length of 20
  }
);

Extra Info

Mongoose allows you to query your collections in different ways like: Official Documentation

// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })

// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })

// passing options and executes
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});

// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});

Solution 6 - Mongoose

For some reason I could not get this to work with the proposed answers, but I found another variation, using select, that worked for me:

models.Post.find().sort('-date').limit(10).select('published').exec(function(e, data){
        ...
});

Has the api perhaps changed? I am using version 3.8.19

Solution 7 - Mongoose

...additionally make sure to use:

mongoose.Promise = Promise;

This sets the mongoose promise to the native ES6 promise. Without this addition I got:

> DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRunning TurtleView Question on Stackoverflow
Solution 1 - MongoosemarniView Answer on Stackoverflow
Solution 2 - MongoosekcbannerView Answer on Stackoverflow
Solution 3 - MongoosetheCodeView Answer on Stackoverflow
Solution 4 - MongooseSuhail AhmedView Answer on Stackoverflow
Solution 5 - Mongooserotimi-bestView Answer on Stackoverflow
Solution 6 - MongooseTGHView Answer on Stackoverflow
Solution 7 - MongooseSchmalitzView Answer on Stackoverflow