146
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?

7 Answers 7

232

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
  });
5
  • 1
    what does {'date': -1} mean? Thanks in advance!
    – kurumkan
    Oct 31, 2016 at 11:55
  • 6
    @ArslArsl - the results will be sorted by the date in decending order.
    – N. L. Long
    Nov 2, 2016 at 15:10
  • @ArslArsl it is similar to the following: { date: 'desc' } {date: 'descending'}. See this answer Apr 30, 2019 at 5:52
  • Is there a max for limit?
    – lukas_o
    Jan 21, 2020 at 9:36
  • I would suggest to do .sort({ createdAt: -1 }) if you want to sort by document creation time
    – Nik B
    Dec 3, 2021 at 19:19
34

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

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

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
});
4
  • 2
    Thanks a lot, didn't know you could make queries like that. Where can I find some form of documentation about this execFind method ? Apr 29, 2011 at 14:18
  • Honestly, I just look at the examples in the mongoose sources and stuff, as well as the test cases. The mailing list is also good. The actual docs seem a bit out of date.
    – kcbanner
    Apr 29, 2011 at 14:25
  • 1
    is execFind still in the latest version of mongoosejs?
    – Manny
    Dec 9, 2013 at 2:32
  • 2
    @Manny It's not. See the marni's answer for an updated version.
    – JohnnyHK
    Dec 15, 2013 at 16:07
10
models.Post.find({published: true}, {sort: {'date': -1}, limit: 20}, function(err, posts) {
 // `posts` with sorted length of 20
});
1
  • 7
    While this code snippet may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post. Remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Feb 7, 2017 at 11:42
6

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) {});
2

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

2

...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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.