用猫鼬获得最新的xx记录,如何订购它们? [英] getting the latest xx records with mongoose, How to order them?

查看:77
本文介绍了用猫鼬获得最新的xx记录,如何订购它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图用猫鼬获取用户集合的最后20条记录:

I'm trying to get the last 20 records of user collection with mongoose:

User.find({'owner': req.params.id}).
sort(date:'-1').
limit(20).
exec(.....)

这很好用,显示最后20个项目.

This works well, show the last 20 items.

但是数组中的项目是从最新到最旧的排序,有没有办法用猫鼬来扭转这种情况?

But the items inside the array are sorted from the most recent to the oldest, Is there any way to reverse this with mongoose?

谢谢

推荐答案

您当然可以通过聚合来做到这一点,例如:

You can certainly do this with an aggregation, such as this:

db.user.aggregate[(
  { $match : {"owner" : req.params.id}},
  { $sort : {"date" : -1}},
  { $limit : 20},
  { $sort : {"date" : 1}}
])

有关此汇总的注意事项:

Notes on this aggregation:

  • 前三个部分与您的问题中的查找"功能相同
  • 第四部分还进行了进一步的排序,将返回的20条记录从最早的记录重新排列到最新的记录
  • 我已使用本机 MongoDB聚合语法编写了该代码;您将需要调整代码以从猫鼬生成相同的聚合.
  • The first three parts do the same job as the Find in your question
  • The fourth part applies a further sort, which re-orders the returned 20 records from oldest to most recent
  • I have written it in native MongoDB aggregation syntax; you will need to adjust the code to generate the same aggregation from Mongoose.

更新:我认为使用使用游标方法查找(),因为您需要两个不同的sort()操作.但是,MongoDB不会将它们视为一系列独立操作;文档给出了以一个顺序-sort().limit()-等效于相反顺序-limit().sort()编写方法的示例,表明该顺序不能被认为是有意义的.

Update: I think this is not possible with a find() with cursor methods, because you would need two different sort() operations. But, MongoDB does not treat them as a sequence of independent operations; the docs give an example of methods written in one order — sort().limit() — being equivalent to the opposite order — limit().sort(), showing that the order cannot be relied upon as meaningful.

这篇关于用猫鼬获得最新的xx记录,如何订购它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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