简体   繁体   English

查找最近日期的所有记录,mongoDB,mongoose

[英]Find all records for the latest date, mongoDB, mongoose

How would I find all items from the latest date in MongoDB? 我如何在MongoDB中找到最近日期的所有项目? I'm using mongoose as well. 我也在用猫鼬。 I also need I way to store date in format DD.MM.YYYY. 我还需要以DD.MM.YYYY格式存储日期的方法。 I use Date.now and it's saves time as well 我使用Date.now,它也节省了时间

For your first question, you have two options: 对于第一个问题,您有两个选择:

  1. First you can make a query at the collection with sort operation all results by date, then store the first date at a variable and then you have to iterate all the results one by one until the date of the entry is different. 首先,您可以使用按日期对所有结果进行排序操作在集合中进行查询,然后将第一个日期存储在变量中,然后必须逐个迭代所有结果,直到条目的日期不同为止。
  2. You can make a aggregation query for that. 您可以为此进行汇总查询。 For example: 例如:

    db.collection.aggregate([ { $group:{ _id:{ year: { $year: "$date" }, month: { $month: "$date" },day: { $dayOfMonth: "$date" }, 'objects':{ $push : '$$ROOT' } }, 'date':{ $last:'$date' } } }, { $sort: { 'date':-1 } }, { $limit : 1 } ]) db.collection.aggregate([{$ group:{_id:{year:{$ year:“ $ date”},month:{$ month:“ $ date”},day:{$ dayOfMonth:“ $ date”} ,'objects':{$ push:'$$ ROOT'}},'date':{$ last:'$ date'}}},{$ sort:{'date':-1}},{$ limit :1}])

And finally for your second question, you can make the "translation" of the date at your code so you have not to save that format at database. 最后,对于第二个问题,您可以在代码中对日期进行“翻译”,因此不必在数据库中保存该格式。

My suggestions are for mongodb code and, maybe, there is easiest way in mongoose. 我的建议是针对mongodb代码,也许,在mongoose中有最简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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