使用node.js从MongoDB中选择最后N条记录 [英] Select last N records from MongoDB using node.js

查看:86
本文介绍了使用node.js从MongoDB中选择最后N条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我已经看到了其他问题并尝试了运气,没有运气.

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

我在MongoDB中有一个集合:

I have a collection in MongoDB:

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

我需要从category_id中查找等于 10 的最后10个条目.听起来很简单?

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

但是运行该命令可以得到10个记录,而不是最后10个记录,而我却得到了第一条记录.看起来驱动程序具有限制"而不是排序"的优先级...我也尝试使用$natural并进行排序time_added.每当我从命令行运行相同的查询时,我都会得到所需的信息.这是我在命令行中键入的内容:

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)

我做错了什么?有没有其他方法可以使用node.js做到这一点?

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

推荐答案

结果证明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) {})

这篇关于使用node.js从MongoDB中选择最后N条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆