Home > Enterprise >  get difference between two dates in years in mongo db
get difference between two dates in years in mongo db

Time:10-04

I have the following document

   {
      name: "Pedro",
      birthdate: ISODate("1987-05-18T00:00:00Z"),
    }

I'm starting with mongo and I need to return the name, date of birth and age. how do I get the age in years? I've been trying this way

db.Pessoa.aggregate( [ { $project: { name: 1, birthdate:1, dateDifference: { $subtract: [ new Date(), "$birthdate" ] } } } ] )

CodePudding user response:

Perform a simple $dateDiff with endDate: "$$NOW". Set unit to be year to get difference in years.

db.collection.aggregate([
  {
    $project: {
      name: 1,
      birthdate: 1,
      dateDifference: {
        "$dateDiff": {
          "startDate": "$birthdate",
          "endDate": "$$NOW",
          "unit": "year"
        }
      }
    }
  }
])

Here is a Mongo Playground for your reference.

  • Related