Mongo Aggregation $subtract :对于两个非空日期总是给出空结果

Posted

技术标签:

【中文标题】Mongo Aggregation $subtract :对于两个非空日期总是给出空结果【英文标题】:Mongo Aggregation $subtract : Always gives null result for two non empty dates 【发布时间】:2022-01-22 21:46:33 【问题描述】:

我想获取一系列员工工作纪念日的列表。 加入日期在员工记录中可用。 在此查询中,首先计算今年的 aniversaryDate,然后尝试找出今天日期和周年日期之间的差异。但是$subtract 对所有记录集都返回 false。

db.employees.aggregate([
    "$match":  "deleted": false 
,

    "$project": 
        "id": 1, "firstName": 1, "lastName": 1, "empId": 1, "joiningDate": 1,
        "aniversaryDate":
            
                "$dateFromParts":
                    
                        "year":  "$year": "$$NOW" ,
                        "day":  "$dayOfMonth": "$joiningDate" ,
                        "month":  "$month": "$joiningDate" 
                    
            ,
        "dateDifference":
             "$subtract": ["$aniversaryDate", "$$NOW"] 


    
,  "$sort":  "dateDifference": 1  ]);

结果给出了这样的对象数组:


    "_id" : ObjectId("61a4bf6b5362437b668db2b5"),
    "empId" : "1",
    "firstName" : "Olive",
    "lastName" : "Gunter",
    "joiningDate" : ISODate("2021-10-03T16:16:58.997+05:30"),
    "aniversaryDate" : ISODate("2021-10-03T05:30:00.000+05:30"),
    "dayssince" : null,
    "dateDifference" : null

【问题讨论】:

【参考方案1】:

您需要另一个$project 阶段来获得aniversaryDate,它是从前一个$project 阶段生成的。

db.collection.aggregate([
  
    "$match": 
      "deleted": false
    
  ,
  
    "$project": 
      "id": 1,
      "firstName": 1,
      "lastName": 1,
      "empId": 1,
      "joiningDate": 1,
      "aniversaryDate": 
        "$dateFromParts": 
          "year": 
            "$year": "$$NOW"
          ,
          "day": 
            "$dayOfMonth": "$joiningDate"
          ,
          "month": 
            "$month": "$joiningDate"
          
        
      ,
    
  ,
  
    $project: 
      "dateDifference": 
        "$subtract": [
          "$aniversaryDate",
          "$$NOW"
        ]
      
    
  ,
  
    "$sort": 
      "dateDifference": 1
    
  
])

Sample Mongo Playground


如果您使用的是 MongoDB 版本 5,则可以替换为 $dateDiff


  $project: 
    "dateDifference": 
      "$dateDiff": 
        "startDate": "$aniversaryDate",
        "endDate": "$$NOW",
        "unit": "day"
      
    
  

Sample Mongo Playground (with $dateDiff)

【讨论】:

我无法更新 mongo 版本,所以我将使用 $subtract

以上是关于Mongo Aggregation $subtract :对于两个非空日期总是给出空结果的主要内容,如果未能解决你的问题,请参考以下文章

开发中使用mongoTemplate进行Aggregation聚合查询

mongodb Aggregation聚合操作之$sort

mongodb Aggregation聚合操作之$bucket

mongodb Aggregation聚合操作之$facet

aggregation 详解3(bucket aggregation)

Aggregation:BlendingBaggingRandom Forest