在mongodb中的文档嵌套数组中查找状态总和 [英] Find sum of status in nested array of document in mongodb

查看:88
本文介绍了在mongodb中的文档嵌套数组中查找状态总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的文档结构中,我需要找到数组"X"中的元素总数以及"X"中状态"a"的总数.

In the below document structure I need to find total number of element in array 'X' and total counts of status 'a' in 'X'.

 [
      {
        X: [
          {
            Y: [
              {
                STATUS: "a"
              },
              {
                STATUS: "b"
              },
              {
                STATUS: "c"
              }
            ]
          },
          {
            Y: [
              {
                STATUS: "a"
              },
              {
                STATUS: "b"
              },
              {
                STATUS: "c"
              }
            ]
          }
        ]
      }
    ]

此处所需的结果将是'X'中元素的总数为2,而'X'中状态'a'的总数为2.

here the required result would be total no of element in 'X' is 2 and total no of status 'a' inside 'X' is 2.

已尝试但无法在单个查询中获取准确的数据.

In tried but not able to get exact data in a single query.

推荐答案

您需要 $ size 获取数组和 $ reduce 来简单地将所有内容相加a用于X数组.试试:

You need $size to get the length of array and $filter to apply STATUS a condition. Then you can use $reduce to simply sum all a for X array. Try:

db.collection.aggregate([
    {
        $project: {
            total_a: { 
                $reduce: {
                    input: "$X",
                    initialValue: 0,
                    in: {
                        $add: [ "$$value", 
                            { $size: { $filter: { input: "$$this.Y", as: "yy", cond: { $eq: [ "$$yy.STATUS", "a" ] } } } } 
                        ]
                    }
                }
            },
            total_X: { $size: "$X" }
        }
    }
])

游乐场此处

这篇关于在mongodb中的文档嵌套数组中查找状态总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆