【发布时间】:2020-06-19 15:14:55
【问题描述】:
我正在尝试编写一个 mongo 聚合查询,它返回每个 年月 集合中的条目总数,按 位置 分组。
这是所需输出的示例:
[
{
_id: 'Location 1',
reviews: [
{ total: 12, date: '03-2019' },
{ total: 55, date: '04-2019' },
{ total: 9, date: '05-2019' }
]
},
{
_id: 'Location 2',
reviews: [
{ total: 8, date: '03-2019' },
{ total: 35, date: '04-2019' },
{ total: 12, date: '05-2019' }
]
}
];
这是架构的截断示例:
{
branchId: { type: String, required: true },
orgId: { type: String, required: true },
stars: { type: Number, default: 0 },
reviewUpdatedAt: { type: Date, default: Date.now }
}
我能够以各种方式返回数据,但在获取所需输出时遇到问题。以下是我遇到障碍的一些示例查询。基本上我在尝试对每月的总条目进行分组时遇到问题,然后按 branchId / location 进一步分组。
以下是按年月分组的示例。响应包含每个 branchId 的计数,但 _ids 对于每个分支的月份-年份都有重复项。我需要 _id 作为位置,并有一个包含总计和年月的数组,如上面所需输出的示例所示。
[
{
$match: {
stars: {$exists: true, $gte: 1},
orgId: '100003'
// reviewUpdatedAt: { $gte: new Date(fromDate), $lte: new Date(toDate) }
}
},
{
$group: {
_id: { $dateToString: { format: '%Y-%m', date: '$reviewUpdatedAt' }},
branchId: {$addToSet: '$branchId'},
total: { $sum: 1 }
}
},
{
$unwind: '$branchId'
},
{ $sort: { _id: 1 } }
]
在上面的示例中,我已经成功调整了组和 $unwind 语句,如下所示:
{
$group: {
_id: '$branchId',
date: { $addToSet: { $dateToString: { format: '%Y-%m', date: '$reviewUpdatedAt' } } },
total: { $sum: 1 }
}
},
{ $unwind: '$date' }
但是,总的 $sum 并不准确,并且对于每个 branchId 条目都会重复。如何修改上述查询以产生所需的输出?任何帮助将不胜感激。
【问题讨论】:
标签: node.js mongodb mongoose mongodb-query aggregation-framework