$ addFields中的日期计算

时间:2019-03-29 20:57:31

标签: mongodb aggregation-framework mongodb-atlas

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

MongoDB版本是Atlas 4.0.6。

给出以下文档结构:

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

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

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

我想用每个文档的$thresholdCount值替换硬编码的(* 4)。我的语法不正确。

下面的代码以 “ message”失败:“无法取消最短持续时间”

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

1 个答案:

答案 0 :(得分:2)

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

因此将ms1w * "$thresholdCount"替换为{ $multiply: [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}
}