Spaniard89
Spaniard89

Reputation: 2419

Limiting the number of documents to be returned while calling the find() function on a collection in mongodb

As my question suggest, I would like to limit the number of documents displayed when the find() function is called on a collection like this:

exports.findAll = function(req, res) {
db.collection('temp', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

The above code will display all the documents present in the temp collection. But is there a way where i could limit the number of documents being displayed to 10? And i would like to send the last ten documents(By last i mean, the ones added lately)

I would really appreciate any suggestions.

Thanks a lot in advance.

Upvotes: 0

Views: 55

Answers (1)

Philipp
Philipp

Reputation: 69663

The method find() returns a database cursor. Database cursors have a limit(n) method, which returns another database cursor which only iterates the first n documents. So you just have to replace the 3rd line with:

collection.find().limit(10).toArray(function(err, items) {

Note that there is no way to be sure that these 10 documents will be selected by any predictable priority. Usually it's insertion order, but this isn't guaranteed. So you should prefix the limit(n) with an appropriate call of .sort(your_sort_criterias).

Upvotes: 2

Related Questions