猫鼬:查找最近的文档 [英] mongoose: find most recent document

查看:30
本文介绍了猫鼬:查找最近的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 mongoose 模式,它的 day 属性就是

I have mongoose schema which has a day attribute which is just

Math.floor((new Date()).getTime() / (24 * 3600 * 1000))

我想找到输入的最后一天的数据,所以说今天是 16085 然后我想找到输入的最后一天.或者另一种说法是.day 属性小于 16085 但大于所有其他文档的文档是什么,其中 day 也小于 16085.

and I want to find the data for the last day entered so say today is 16085 then I want to find the last day entered. Or another way of saying this would be. What is the document with a day attribute less then 16085 but greater then all other documents where day is also less then 16085.

或其他方式

day 属性小于 16085 的所有文档集合的最大元素是什么

What is the maximal element of the set of all documents with a day attribute less then 16085

然后迭代我的所有文档,我怎么能做到这一点?

Other then iterating over all of my documents, how could I do this?

推荐答案

在 shell 中:

db.test.find({day: {$lt: 16085}}).sort({day: -1}).limit(1)

查找day小于16085的所有文档,按day降序排序,然后取第一个.

Which finds all the docs where day is less than 16085, sorts them on day descending, and then takes the first one.

在猫鼬中,它将类似于:

In Mongoose it would be something like:

MyModel.find({day: {$lt: 16085}}).sort({day: -1}).limit(1).exec((err, docs) => { ... });

这篇关于猫鼬:查找最近的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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