首页 > 解决方案 > 如何计算 mongoDB 中嵌入的数组对象元素

问题描述

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

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

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

标签: mongodbmongodb-querynosqlaggregation-framework

解决方案


对于内部数组,您可以使用$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 ]
                                        }
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        }
    }
])

蒙戈游乐场


推荐阅读