【发布时间】: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