如何在mongodb中减去日期和时间?

时间:2018-10-08 20:37:04

标签: mongodb mongodb-query aggregation-framework

我已经创建了一个带有日期和时间的文档

use testing
db.test.insert({employee : 1, DateColumn1: new Date(), DateColumn2: new Date()})

创建文档后,我需要在5分钟后更新DateColumn2。

db.test.update({employee : 1}, {$set : {DateColumn2: new Date()}})

我尝试使用此命令减去DateColumn2-DateColumn1,但显示的是数字格式。

db.test.aggregate([{$project :{employee : 1, dateDifference: {$subtract: ["$DateColumn2","$DateColumn1"]}}}])

我需要显示日期和时间格式

1 个答案:

答案 0 :(得分:0)

db.collection.aggregate([
  {
    $addFields: {
      dateDifference: {
        $subtract: [
          "$DateColumn2",
          "$DateColumn1"
        ]
      }
    }
  },
  {
    $addFields: {
      diffInSec: {
        $divide: [
          "$dateDifference",
          1000
        ]
      }
    }
  },
  {
    $addFields: {
      hours: {
        $floor: {
          $divide: [
            "$diffInSec",
            3600
          ]
        }
      },

    }
  },
  {
    $addFields: {
      remainingSeconds: {
        $subtract: [
          "$diffInSec",
          {
            $multiply: [
              "$hours",
              3600
            ]
          }
        ]
      }
    }
  },
  {
    $addFields: {
      minutes: {
        $floor: {
          $divide: [
            "$remainingSeconds",
            60
          ]
        }
      },

    }
  },
  {
    $addFields: {
      remainingSeconds: {
        $subtract: [
          "$remainingSeconds",
          {
            $multiply: [
              "$minutes",
              60
            ]
          }
        ]
      }
    }
  }
])

您可以here对其进行测试