Select last N records from MongoDB using node.js

2019-01-25 19:44发布

问题:

Note: I have seen the other question and tried answers from it with no luck.

I have a collection in MongoDB:

{ _id: 1, category_id: 1, time_added: 1234567890, name: "abc" }

I need to find last 10 entries from category_id equal to 10. Sound simple?

collection.find({ 'category_id': 10 }, {}, { _id: -1, limit : 10}, function (e, d) {});

But running this gives me first 10 records instead of last 10. Looks like driver has priority to "limit" and not "sorting"... I also tries with $natural and sorting on time_added. Whenever I run the same query from command line - I get what I need. Here is what I type into command line:

collection.find({ 'category_id': 10 }).sort({_id: -1}).limit(10)

What am I doing wrong? Is there an alternative way to do this with node.js?

回答1:

Turns out node.js accepts function calls in the same way the command line interface does. Every function has last optional argument as callback function. So this code runs and returns the correct results:

collection.find({ 'category_id': 10 }).sort({_id: -1}).limit(10, function (e, d) {})