【问题标题】:sum (aggregation) one field in document求和(聚合)文档中的一个字段
【发布时间】:2021-04-13 10:08:22
【问题描述】:

我是初学者 spring-boot 和 mongodb 开发人员 我有类别和类别中的一些内容

       [
        
          {
            _id ="5f9d89f5d7bb2c56b678614b",
            categoryId="5f8066dad0b65b3b9ca67e4b",
            likeCount=10
        },
     {
            _id ="5f9d89f5456b2c56b678614b",
            categoryId="5f8066dad0b65b3b9cnhk44",
            likeCount=5
  }
    {
        ]

我想计算这个文档中的总likeCount,在这个例子中等于15,并显示在类别列表中。 有什么解决办法?

【问题讨论】:

    标签: mongodb spring-boot sum backend aggregation


    【解决方案1】:

    如果你有嵌套数组,你可以这样尝试

    db.collectionName.aggregate([
        {
            "$unwind": "$fieldName"
        },
        {
            $group: {
                _id: null,
                sum: {
                    $sum: "$fieldName.likeCount"
                }
            }
        }
    ])
    
    

    在其他情况下只使用这个

    db.collectionName.aggregate([
        {
            $group: {
                _id: null,
                sum: {
                    $sum: "$likeCount"
                }
            }
        }
    ])
    

    如果您有任何问题,请随时提出。

    【讨论】:

    • 谢谢,但我如何在 Spring Boot 中使用它?
    猜你喜欢
    • 2023-02-11
    • 1970-01-01
    • 2023-03-05
    • 2019-10-25
    • 1970-01-01
    • 2020-11-14
    • 2020-07-23
    • 2020-03-06
    • 2023-03-15
    相关资源
    最近更新 更多