【问题标题】:How to count embedded array object elements in mongoDB如何计算 mongoDB 中嵌入的数组对象元素
【发布时间】:2021-05-12 13:11:43
【问题描述】:
{
    "orderNo": "123",
    "bags": [{
            "type": "small",
            "products": [{
                    "id": "1",
                    "name": "ABC",
                    "returnable": true
                }, {
                    "id": "2",
                    "name": "XYZ"
                }
            ]
        },{
            "type": "big",
            "products": [{
                    "id": "3",
                    "name": "PQR",
                    "returnable": true
                }, {
                    "id": "4",
                    "name": "UVW"
                }
            ]
        }
    ]
}

我有订单集合,其中文档采用这种格式。我想获得具有 returnable 标志的 products 的总数。例如:对于上述顺序,计数应为 2。我对 MongoDB 很陌生,想知道如何编写查询来找出答案,我尝试了几件事,但没有帮助: 这是我尝试过但没有奏效的方法:

db.orders.aggregate([
     { "$unwind": "$bags" },
     { "$unwind": "$bags.products" },
     { "$unwind": "$bags.products.returnable" },
     
     { "$group": {
         "_id": "$bags.products.returnable",
         "count": { "$sum": 1 }
     }}
 ])

【问题讨论】:

  • 您的预期结果是什么?

标签: mongodb mongodb-query nosql aggregation-framework


【解决方案1】:

对于内部数组,您可以使用$filter 检查returnable 标志和$size 以获取此类项目的数量。对于外层,您可以利用 $reduce 对内层数组的值求和:

db.collection.aggregate([
    {
        $project: {
            totalReturnable: {
                $reduce: {
                    input: "$bags",
                    initialValue: 0,
                    in: {
                        $add: [
                            "$$value",
                            {
                                $size: {
                                    $filter: {
                                        input: "$$this.products",
                                        as: "prod",
                                        cond: {
                                            $eq: [ "$$prod.returnable", true ]
                                        }
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        }
    }
])

Mongo Playground

【讨论】:

  • 非常感谢,1 个小问题:如果我想要基于“可返回”属性可用性而不是其真/假值的计数。
  • @Souma 你可以试试这个方法:mongoplayground.net/p/-pe84bP6CfR
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-17
  • 2016-11-05
  • 1970-01-01
  • 2017-05-18
相关资源
最近更新 更多