Convert date difference to years to calculate age in MongoDB

旧城冷巷雨未停 提交于 2020-01-13 06:43:31

问题


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)
   } } 
] )

回答1:


Update: Earlier solution with $let is not required, we can just combine the aggregation operators

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)]
                }
            }
        } 
     } 
} ] )



回答2:


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
   ]}
]}


来源:https://stackoverflow.com/questions/39381450/convert-date-difference-to-years-to-calculate-age-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!