【发布时间】:2019-11-17 08:43:35
【问题描述】:
我有一个聚合查询,它返回为给定位置提交的评论的总和/总数(而不是平均星级)。评论评分为 1 - 5 星。此特定查询将这些评论分为两类,“内部”和“谷歌”。
我有一个查询,它返回的结果几乎就是我正在寻找的结果。但是,我需要为内部审核添加一个附加条件。我想确保内部评论“星”值存在/不为空并且包含至少 1 的值。所以,我想添加类似的东西会起作用:
{ "stars": {$gte: 1} }
这是当前的聚合查询:
[
{
$match: { createdAt: { $gte: fromDate, $lte: toDate } }
},
{
$lookup: {
from: 'branches',
localField: 'branch',
foreignField: '_id',
as: 'branch'
}
},
{ $unwind: '$branch' },
{
$match: { 'branch.org_id': branchId }
},
{
$group: {
_id: '$branch.name',
google: {
$sum: {
$cond: [{ $eq: ['$source', 'Google'] }, 1, 0]
}
},
internal: {
$sum: {
$cond: [ { $eq: ['$internal', true]}, 1, 0 ],
},
}
}
}
]
截断模式:
{
branchId: { type: String, required: true },
branch: { type: Schema.Types.ObjectId, ref: 'branches' },
wouldRecommend: { type: String, default: '' }, // RECOMMENDATION ONLY
stars: { type: Number, default: 0 }, // IF 1 - 5 DOCUMENT IS A REVIEW
comment: { type: String, default: '' },
internal: { type: Boolean, default: true },
source: { type: String, required: true },
},
{ timestamps: true }
我需要确保我没有将“wouldRecommend”建议计入内部评论的总和中。确定某件事是否是评论,它将有 1 星或更多星的星级。推荐的星级值为 0。
如何添加确保内部“$stars”值 >= 1(大于或等于 1)的条件?
使用 Ashh 的回答,我能够形成这个查询:
[
{
$lookup: {
from: 'branches',
localField: 'branch',
foreignField: '_id',
as: 'branch'
}
},
{ $unwind: '$branch' },
{
$match: {
'branch.org_id': branchId
}
},
{
$group: {
_id: '$branch.name',
google: {
$sum: {
$cond: [{ $eq: ['$source', 'Google'] }, 1, 0]
}
},
internal: {
$sum: {
$cond: [
{
$and: [{ $gte: ['$stars', 1] }, { $eq: ['$internal', true] }]
},
1,
0
]
}
}
}
}
];
【问题讨论】:
标签: javascript mongodb mongoose mongodb-query aggregation-framework