我有包含具有以下架构的文档的集合。
架构
{
"categoryId": "1234",
"sellerId": "2323",
"productId": "121",
"rating": 1
},
{
"categoryId": "1235",
"sellerId": "2323",
"productId": "122",
"rating": -1
},
{
"categoryId": "1234",
"sellerId": "2323",
"productId": "123",
"rating": -1
},
{
"categoryId": "1235",
"sellerId": "2323",
"productId": "124",
"rating": 1
},
{
"categoryId": "1234",
"sellerId": "2323",
"productId": "125",
"rating": 1
},
{
"categoryId": "1234",
"sellerId": "2325",
"productId": "125",
"rating": 1
}
评级可以有值1
或-1
。我想找到按categoryId
评分和总和分组的所有文档。示例结果:
{categoryId: 1234, positiveRatingCount: 2, negativeRatingCount: 1}
这是我到目前为止所做的:
ratingsCollection.aggregate(
{
$match: {sellerId: "2323" }
},
{
$group: {
_id: "$categoryId",
count: { $sum: "rating" }
}
}
);
我得到以下结果。我能够按类别分组,但无法计算出正面和负面评级的数量。
[
{
"_id": "1234",
"count": 3
},
{
"_id": "1235",
"count": 2
}
]
您需要$sum
与条件($cond
)一起使用,其中rating
is$gt
或$lt
then 0
db.collection.aggregate([
{ "$match": { "sellerId": "2323" } },
{ "$group": {
"_id": "$categoryId",
"positiveRatingCount": {
"$sum": { "$cond": [{ "$gt": [ "$rating", 0 ] }, "$rating", 0 ] }
},
"negativeRatingCount": {
"$sum": { "$cond": [{ "$lt": [ "$rating", 0 ] }, "$rating", 0 ] }
}
}}
])
[
{
"_id": "1235",
"negativeRatingCount": -1,
"positiveRatingCount": 1
},
{
"_id": "1234",
"negativeRatingCount": -2,
"positiveRatingCount": 3
}
]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句