Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
959 views
in Technique[技术] by (71.8m points)

javascript - mongoose: find most recent document

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

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

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.

or another way

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the shell it would be:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...