如何在mongodb中对group by使用聚合

时间:2018-08-25 05:02:30

标签: mongodb aggregation-framework

我有一个包含以下模式文档的集合。

架构

{
    "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
    }
]

1 个答案:

答案 0 :(得分:2)

您需要在rating$sum$cond然后 0 的条件($gt)下使用$lt

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 ] }
    }
  }}
])

Output

[
  {
    "_id": "1235",
    "negativeRatingCount": -1,
    "positiveRatingCount": 1
  },
  {
    "_id": "1234",
    "negativeRatingCount": -2,
    "positiveRatingCount": 3
  }
]
相关问题