margarita
margarita

Reputation: 27

Get the latest year in MongoDB

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!

Upvotes: 0

Views: 114

Answers (2)

Constantine
Constantine

Reputation: 680

You can use $group (aggregation)

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

Upvotes: 0

R2D2
R2D2

Reputation: 10737

This is pretty fast:

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

Upvotes: 1

Related Questions