$addFields 中的日期计算

date calculations in $addFields

我想在聚合管道的 $addFields 阶段执行日期计算。这适用于硬编码乘法器,但如果我尝试从文档传递值,则会失败。

MongoDB版本是Atlas 4.0.6。

鉴于此文档结构:

{
    "_id" : ObjectId("5c9e78c61c9d440000a83cca"),
    "title" : "InterventionA",
    "thresholdCount" : 4,
    "thresholdUnit" : "weeks"
},
{
    "_id" : ObjectId("5c9e7d361c9d440000a83ccb"),
    "title" : "InterventionB",
    "thresholdCount" : 4,
    "thresholdUnit" : "days"
}

..此查询有效。请注意 (*4) 中的乘数 $cond 是硬编码的。

const endDate = new Date();
endDate.setHours(0, 0, 0, 0);

const ms1d = 24 * 60 * 60 * 1000;   /* milliseconds per day */
const ms1w = 7 * ms1d;              /* milliseconds per week */

db.stackex.aggregate([
  {
    $addFields: {
      dateRange: {
        $cond: {
          if: { $eq: ["$thresholdUnit", "weeks"] },
          then: { "start": { $subtract: [endDate, ms1w * 4] }, "end": endDate},
          else: { "start": { $subtract: [endDate, ms1d * 4] }, "end": endDate}
        }
      }
    }
  }
]);

期望的结果是:

{
    "_id" : ObjectId("5c9e78c61c9d440000a83cca"),
    "title" : "InterventionA",
    "thresholdCount" : 4,
    "thresholdUnit" : "weeks",
    "dateRange" : {
        "start" : ISODate("2019-02-28T23:00:00.000-08:00"),
        "end" : ISODate("2019-03-29T00:00:00.000-07:00")
    }
},
{
    "_id" : ObjectId("5c9e7d361c9d440000a83ccb"),
    "title" : "InterventionB",
    "thresholdCount" : 4,
    "thresholdUnit" : "days",
    "dateRange" : {
        "start" : ISODate("2019-03-25T00:00:00.000-07:00"),
        "end" : ISODate("2019-03-29T00:00:00.000-07:00")
    }
}

我想将每个文档的硬编码 (* 4) 替换为 $thresholdCount 的值。我的语法不对。

下面的代码因 "message" 失败:"Cannot negate the minimum duration"

const endDate = new Date();
endDate.setHours(0, 0, 0, 0);

const ms1d = 24 * 60 * 60 * 1000;   /* milliseconds per day */
const ms1w = 7 * ms1d;              /* milliseconds per week */

db.stackex.aggregate([
  {
    $addFields: {
      dateRange: {
        $cond: {
          if: { $eq: ["$thresholdUnit", "weeks"] },
          then: { "start": { $subtract: [endDate, ms1w * "$thresholdCount"] }, "end": endDate},
          else: { "start": { $subtract: [endDate, ms1d * "$thresholdCount"] }, "end": endDate}
        }
      }
    }
  }
]);

您需要使用$multiply运算符进行乘法计算。

所以用{ $multiply: [ms1w, "$thresholdCount"] }

替换ms1w * "$thresholdCount"

这里是完整的 $cond 表达式:

$cond: {
    if: { $eq: ["$thresholdUnit", "weeks"] },
    then: { "start": { $subtract: [endDate, { $multiply: [ms1w, "$thresholdCount"] } ] }, "end": endDate},
    else: { "start": { $subtract: [endDate, { $multiply: [ms1d, "$thresholdCount"] } ] }, "end": endDate}
}