【问题标题】:Mongoose aggregate - $subtract datesMongoose 聚合 - $subtract 日期
【发布时间】:2015-06-28 07:42:17
【问题描述】:

我在尝试减去两个日期以获得毫秒差异时遇到了 Mongoose 聚合问题。

这是文档的结构:

DeliverySchema = new mongoose.Schema({
  hash: String,
  status: Number,
  insertedOn: {
    type: Date,
    default: Date.now
  },
  endedOn: {
    type: Date
  }
}, {
  collection: 'Deliveries'
});

这是查询:

var Delivery = mongoose.model('Delivery');

return Delivery.aggregate([
    {
      $match: {
        'insertedOn': {$ne: null, $type: 9},
        'endedOn': {$ne: null, $type: 9}
      }
    },
    {$project: {duration: {$subtract: ["$endedOn", "$insertedOn"]}}},
    {
      $group: {
        _id: {
          day: {$dayOfMonth: "$insertedOn"},
          month: {$month: "$insertedOn"},
          year: {$year: "$insertedOn"}
        },
        count: {$sum: 1},
        durationAvg: {$avg: "$duration"}
      }
    },
    {$sort: {"_id.year": 1, "_id.month": 1, "_id.day": 1}}
  ])

这是我得到的错误:

error: exception: can't convert from BSON type EOO to Date

$match 阶段应该过滤所有 insertOn/endedOn 字段为 null 或非 Date 的文档,但它似乎没用。我被卡住了,有人有任何线索吗? 我正在使用带有节点 0.10.33 的 Mongoose 4.0.1(托管在 Mongolab 上的 mongod 2.6.9)。 谢谢

谢谢。

【问题讨论】:

  • 发生这种情况的一种方法是,如果您有一个文档,其中insertedOnendedOn 包含一个包含Datearray。此外,null 是单独的类型,因此您不需要 $match 对象中的 $ne: null 部分。
  • 你是对的,$match$ne: null 部分是没用的。我的文档都不包含日期数组,实际上我也尝试使用单个文档,其中 insertedOnendedOn 字段都填充了日期,我得到了完全相同的错误。
  • 好的,我想我现在看到了问题所在。您需要在$project 中包含insertedOnendedOn 字段。现在,它只是一个 duration 字段。

标签: node.js mongodb mongoose


【解决方案1】:

$project 阶段的输出是仅包含计算的 duration 字段的文档。您还需要包含 insertedOnendedOn 字段,以便它们可用于随后的 $group 阶段:

{$project: {
    duration: {$subtract: ["$endedOn", "$insertedOn"]},
    endedOn: 1,
    insertedOn: 1
}}

【讨论】:

  • 是的。这就是解决方案。谢谢@JohnnyHK,你拯救了我的一天:-)
猜你喜欢
  • 2017-10-07
  • 2021-10-16
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 2016-06-09
  • 2019-04-15
  • 2014-05-25
  • 2020-12-24
相关资源
最近更新 更多