【问题标题】:Mongo Aggregation ignoring date range filter in $matchMongodb聚合忽略$match中的日期范围过滤器
【发布时间】:2019-09-23 13:56:06
【问题描述】:

我有一个 Mongo 聚合查询,它返回正确的结果,但 $match 中提供的日期范围除外。无论有无日期范围值,它基本上都会返回相同的结果。基本上,我试图确定特定日期每个位置的传递消息总数。

const startOfToday = moment()
  .startOf('day')
  .tz('America/New_York')

const endOfToday = moment()
  .endOf('day')
  .tz('America/New_York')

// Show Todays Entries Only
let fromDate = new Date(startOfToday);
let toDate = new Date(endOfToday);

  Model.aggregate([
  {
    $match: {
      'analytics.twilio.status': 'delivered',
      'analytics.twilio.date': { $gte: fromDate },
      'analytics.twilio.date': { $lte: toDate }
    }
  },
  {
    $lookup: {
      from: 'branches',
      localField: 'branch',
      foreignField: '_id',
      as: 'branch'
    }
  },
  {
    $match: {
      'branch.0.org_id': orgId
    }
  },
  { $unwind: '$branch' },
  {
    $group: {
      _id: '$branch.name',
      delivered: { $sum: 1 }
    }
  }
])
  .sort('_id')
  .then(response => {
    if (response) {
      res.json(response);
    }
  });
 });

这是架构的截断版本:

const Wip =  new Schema({
      branch: {
        type: Schema.Types.ObjectId,
        ref: 'branches'
      },
      analytics: {
        twilio: {
          sid: { type: String },
          status: { type: String },
          error: { type: String },
          date: { type: Date }
        }
      },
        date: { type: Date, default: Date.now }
      });

    const BranchSchema = new Schema({
        name: { type: String, required: true },
        org_id: { type: String, required: true },
        clinic_id: { type: String, required: true },
    })

我认为问题可能是 $lookup,但如果我删除 $lookup 并将 $branch 字段用作 $group id,问题仍然存在。

我忽略了什么?我需要添加某种 $cond 吗?

【问题讨论】:

  • 好的,也向我们展示架构
  • @AnthonyWinzlet 我添加了一个带有相关信息的示例截断模式。

标签: node.js mongodb mongoose aggregation-framework


【解决方案1】:

您需要将 $gte$lte 都包含在单个花括号中

Model.aggregate([
  {
    $match: {
      'analytics.twilio.status': 'delivered',
      'analytics.twilio.date': { '$gte': fromDate, '$lte': toDate }
    }
  }
])

【讨论】:

  • 我是否遗漏了什么,或者您是否只将 .toDate() 添加到时刻值?我试过没有运气。我刚刚将 .toDate() 添加到 moment() 对象并获得相同的结果。我将更新示例。
  • 我认为添加 .toDate() 并在时刻日期周围加上 new Date() 本质上是一回事。但无论哪种方式,都会得到相同的结果。我什至可以设置未来的日期,它显示的结果好像日期没有任何意义。
  • 是的,你是对的。现在明白了。更新了我的答案。
  • 谢谢,我之前遇到过这个问题,这次没有注意到/考虑它。再次感谢。敏锐的眼光。
猜你喜欢
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多