简体   繁体   中英

Find all records for the latest date, mongoDB, mongoose

How would I find all items from the latest date in MongoDB? I'm using mongoose as well. I also need I way to store date in format DD.MM.YYYY. I use Date.now and it's saves time as well

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 } ])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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