【问题标题】:MongoDB date math with aggregation variable带有聚合变量的 MongoDB 日期数学
【发布时间】:2020-08-31 07:13:30
【问题描述】:

我正在尝试构建某个间隔(心跳)未报告的事物的聚合 - 我需要根据存储的心跳计算一个值:

db.things.aggregate([ 
  {$project: {"lastmsg":1, "props.settings":1}}, 
  {$unwind: "$props.settings"},
  {$project: {
    _id:0, 
    "lastmsg": "$lastmsg", 
    "heartbeat": {$multiply: [{$toInt: "$props.settings.heartbeat"},2000]},
    "now": new Date(), "subtracted": new Date(new Date().getTime()- "$heartbeat")
  }
} 
])

返回结果如下:

{ "lastmsg" : ISODate("2020-04-23T12:41:37.667Z"), "heartbeat" : 240000, "now" : ISODate("2020-05-14T16:26:11.824Z"), "subtracted" : ISODate("1970-01-01T00:00:00Z") }
{ "lastmsg" : ISODate("2020-05-14T16:24:24.228Z"), "heartbeat" : 240000, "now" : ISODate("2020-05-14T16:26:11.824Z"), "subtracted" : ISODate("1970-01-01T00:00:00Z") }

“减去”的投影未按预期进行日期数学运算。我可以插入一个特定的数字,它可以工作,但这违背了目的......

作为最后一步,我将匹配以查看在心跳间隔内未签入的这些内容:

  { $match: { "lastmsg":{$gte: "$subtracted")}

任何帮助将不胜感激...

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    我不知道您的数据是什么样的(您应该发布您的数据以提供帮助),但我认为这可以解决问题。
    您可以使用$$NOW 变量,它以ISODate 格式返回当前日期。

    测试数据:

    [
      {
        "lastmsg": ISODate("2020-04-23T12:41:37.667Z"),
        "heartbeat": 240000
      },
      {
        "lastmsg": ISODate("2020-05-14T16:24:24.228Z"),
        "heartbeat": 240000
      }
    ]
    

    查询:

    db.collection.aggregate([
      {
        $addFields: {
          "now": "$$NOW",
          "subtracted": {
            $subtract: [
              "$$NOW",
              "$heartbeat"
            ]
          }
        }
      },
      {
        $match: {
          "lastmg": {
            $gte: "$subtracted"
          }
        }
      }
    ])
    

    【讨论】:

    • 显然这在 Mongo 4.0.10 上不可用 - 无法访问 $$NOW 但将尝试使用 addFields 和/或 $subtract 构建它
    • subtract 做我想要的日期减法,谢谢!!
    • 是的,$subtract 也适用于日期字段。很高兴我帮助了你:D
    猜你喜欢
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2010-11-13
    相关资源
    最近更新 更多