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

前端 未结 5 760
面向向阳花
面向向阳花 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条回答
  • 2020-12-13 00:07

    for version ~3.8 mongoose

    to find the last entry

    model.findOne().sort({ field: 'asc', _id: -1 }).limit(1)
    

    or using

    model.findOne().sort({ field: -_id }).limit(1)
    
    0 讨论(0)
  • 2020-12-13 00:07
    collectionName.findOne().sort({$natural: -1}).limit(1).exec(function(err, res){
        if(err){
            console.log(err);
        }
        else{
            console.log(res);
        }
    }
    

    This will give you the last document recorded on the database. Just follow the same concept.

    0 讨论(0)
  • 2020-12-13 00:08

    Mongoose 3.x is complaining about the [] parameter in your findOne calls as the array format is no longer supported for the parameter that selects the fields to include.

    Try this instead to find the newest:

    Tweet.findOne({}, {}, { sort: { 'created_at' : -1 } }, function(err, post) {
      console.log( post );
    });
    

    Change the -1 to a 1 to find the oldest.

    But because you're not using any field selection, it's somewhat cleaner to chain a couple calls together:

    Tweet.findOne().sort({created_at: -1}).exec(function(err, post) { ... });
    

    Or even pass a string to sort:

    Tweet.findOne().sort('-created_at').exec(function(err, post) { ... });
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-13 00:29

    We have method called sort using that we can able to get first element(old document) which means 1 for sort field or last element(new document) which means -1 for sort field of collection.

    0 讨论(0)
提交回复
热议问题