将日期差异转换为年份以计算MongoDB中的年龄 [英] Convert date difference to years to calculate age in MongoDB

查看:664
本文介绍了将日期差异转换为年份以计算MongoDB中的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下方法计算时间戳差异中的年龄.

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

我在dateDifference中得到了数值.我想通过将其除以(365 * 24 * 60 * 60 * 1000)将其转换为年份.但是我不知道如何在上面的查询中指定此公式.我已经尝试了以下方法,但是它不返回任何值

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

推荐答案

更新:不需要$ let的早期解决方案,我们可以将聚合运算符组合在一起

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


$ let的旧解决方案


Old solution with $let

我能够使用$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)]
                }
            }
        } 
     } 
} ] )

这篇关于将日期差异转换为年份以计算MongoDB中的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆