简体   繁体   中英

Select last N records from MongoDB using node.js

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM