How to get the latest and oldest record in mongoose.js (or just the timespan between them)

前端 未结 5 763
面向向阳花
面向向阳花 2020-12-12 23:59

Basic problem

I have a bunch of records and I need to get latest (most recent) and the oldest (least recent).

When googling I found this topic where I saw

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 00:25

    Fast and Simple - One Line Solution

    Get 10 latest documents

    MySchema.find().sort({ _id: -1 }).limit(10)
    

    Get 10 oldest documents

    MySchema.find().sort({ _id: 1 }).limit(10)
    

    In case you want sorting based on some other property i.e. createdAt and get the oldest or latest. Again it is similar to the above query.

    MySchema.find().sort({ createdAt: 1 }).limit(10)  // oldest docs
    MySchema.find().sort({ createdAt: -1 }).limit(10) // latest docs
    

提交回复
热议问题