Home > Back-end >  Get the latest year in MongoDB
Get the latest year in MongoDB

Time:11-11

While working on a project, I came across a problem that I can't seem to find the solution for anywhere.

I'm working with NoSQLBooster for MongoDB and I need to fetch the most recent year present in my data. I don't want to sort it in a descending way (doing so shows me all the values, and I can see that the year 2018 is the latest), but I want it to just present the number 2018. Does anyone know how I can do this?

Thank you in advance!

CodePudding user response:

This is pretty fast:

var x=  db.find({},{_id:1}).sort(_id:-1).limit(1)
 x._id.getTimestamp()

CodePudding user response:

You can use $group (aggregation)

db.aggregate(
  [
    {
      $group :
        {
          _id : null,
          maxYear: { $max: "$yearField" }
        }
     }
   ]
 )
  • Related