【问题标题】:How to use aggregate for group by in mongodb如何在mongodb中使用聚合进行分组
【发布时间】:2019-01-31 12:12:47
【问题描述】:

我的集合包含具有以下架构的文档。

架构

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

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您需要使用$sum 和条件($cond),其中rating$gt$lt 然后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 ] }
        }
      }}
    ])
    

    Output

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

    【讨论】:

    • 非常感谢,这正是我想要实现的目标。
    猜你喜欢
    • 2019-05-19
    • 1970-01-01
    • 2020-11-16
    • 2020-09-15
    • 2018-06-26
    • 2023-01-20
    • 2019-06-29
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多