5

I am using following to calculate age in timestamp difference.

db.getCollection('person').aggregate( [
  { $project: { 
    item: 1, 
    DOB: "$personal.DOB",
    dateDifference: { $subtract: [ new Date(), "$personal.DOB" ] }
  } } 
] )

I get the numeric value in dateDifference. I want to convert it to years by dividing it with (365*24*60*60*1000). But I don't know how to specify this formula in above query. I have tried the following, but it does not return any value

db.getCollection('person').aggregate( [ 
  { $project: { 
    item: 1, 
    DOB:"$personal.DOB", 
    dateDifference: ({ $subtract: [ new Date(), "$personal.DOB" ] })/(365*24*60*60*1000)
   } } 
] )
Vince Bowdren
  • 8,326
  • 3
  • 31
  • 56
sidgate
  • 14,650
  • 11
  • 68
  • 119

4 Answers4

11

Update: MongoDB 5.0 solution, will consider leap years as well

db.collection.aggregate([
  { $addFields:
    { age: { $dateDiff: { startDate: "$dob", endDate: "$$NOW", unit: "year" } } }
  }
])

Update: We can just combine the aggregation operators. Note that this solution won't give accurate result as it does not consider leap years

db.getCollection('person').aggregate( [ { 
    $project: { 
        date:"$demographics.DOB", 
        age: { 
            $divide: [{$subtract: [ new Date(), "$Demographics.DOB" ] }, 
                    (365 * 24*60*60*1000)]
        } 
     } 
} ] )

Old solution with $let


I was able to solve the issue with $let expression

db.getCollection('person').aggregate( [ { 
    $project: { 
        item: 1, 
        date:"$demographics.DOB", 
        age: { 
            $let:{
                vars:{
                    diff: { 
                        $subtract: [ new Date(), "$demographics.DOB" ] 
                    }
                },
                in: {
                    $divide: ["$$diff", (365 * 24*60*60*1000)]
                }
            }
        } 
     } 
} ] )
sidgate
  • 14,650
  • 11
  • 68
  • 119
4

The accepted answer is incorrect by as many days as there are a leap years that passed since the person was born. Here's a more correct way to calculate age:

{$subtract:[
   {$subtract:[{$year:"$$NOW"},{$year:"$dateOfBirth"}]},
   {$cond:[
      {$gt:[0, {$subtract:[{$dayOfYear:"$$NOW"},
      {$dayOfYear:"$dateOfBirth"}]}]},
      1,
      0
   ]}
]}
Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
4

Starting in Mongo 5.0, it's a perfect use case for the new $dateDiff aggregation operator:

// { "dob" : ISODate("1990-03-27") }
// { "dob" : ISODate("2008-08-07") }
db.collection.aggregate([
  { $addFields:
    { age: { $dateDiff: { startDate: "$dob", endDate: "$$NOW", unit: "year" } } }
  }
])
// { "dob" : ISODate("1990-03-27"), "age" : 31 }
// { "dob" : ISODate("2008-08-07"), "age" : 13 }

This nicely fits the age scenario since (quoting the documentation) durations produced by $dateDiff are measured by counting the number of times a unit boundary is passed. For example, two dates that are 18 months apart would return 1 year difference instead of 1.5 years.

Also note that $$NOW is a variable that returns the current datetime value.

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
  • I am getting the following error with MongoDB 5.0.15: InvalidPipelineOperator Invalid $addFields :: caused by :: Unrecognized expression '$dateDiff' – Thomas Mar 16 '23 at 09:46
  • Hard to explain, the documentation says it's available as of version 5.0, but maybe your minor version's still too early. https://www.mongodb.com/docs/v5.0/reference/operator/aggregation/dateDiff/#mongodb-expression-exp.-dateDiff – Xavier Guihot Mar 16 '23 at 10:03
0

Update 2022: If the mongo version < 5. This query filters user whose ages are above 65+. Playground

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          {
            $let: {
              vars: {
                diff: {
                  $subtract: [
                    new Date(),
                    {
                      "$toDate": "$birthday"
                    }
                  ]
                }
              },
              in: {
                $divide: [
                  "$$diff",
                  {
                    $multiply: [
                      365,
                      24,
                      60,
                      60,
                      1000
                    ]
                  }
                ]
              }
            }
          },
          65
        ]
      }
    }
  },
  
])
Taha Farooqui
  • 637
  • 10
  • 25