Mongodb数组对象按值计数

时间:2015-10-04 15:40:26

标签: mongodb

我有以下结构的json

db.testCollection.insert(
{
  "m_id": 2,
  "sys_data":[
    {"sattr": 
      {
        "size": 2,
        "d_data":
        [
          {"d_counter": 2,
          "client_ip":"1.1.1.1",
          "d_date":"02/01/01"}
          {"d_counter": 2,
          "client_ip":"1.1.1.1",
          "d_date":"02/01/01"}
          {"d_counter": 2,
          "client_ip":"1.1.1.1",
          "d_date":"03/01/01"}
        ]
      }
    }
  ]
}

db.testCollection.insert(
{
  "m_id": 2,
  "sys_data":[
    {"sattr": 
      {
        "size": 2,
        "d_data":
        [
          {"d_counter": 2,
          "client_ip":"1.1.1.1",
          "d_date":"02/01/01"}
       ]
      }
    }
  ]
}

我想得到d_date =' 02/01/01'的计数,所以上面json的输出是3.(第一个json两个,第二个一个)

2 个答案:

答案 0 :(得分:0)

查看此docs from mongodb

cq.select(cb.count(cb.construct(......)));
// Failed because count accepts Expression and I tried assigning the cb.construct to Expression which is not working.

此外,上述内容相当于:

db.testCollection.count( { d_date : "02/01/01"  } )

如果您觉得性能检查缓慢this question

答案 1 :(得分:0)

使用 aggregation framework 来计算。这样,您就可以 $unwind 深层嵌套的嵌入式文档(在 dot notation 的帮助下),使用 $match 运算符,类似于 find() 查询,并使用{{> $sum 累加器运算符{{ 3}}管道确定匹配文件的数量。

这样的事情:

填充测试集合:

db.testCollection.insert([
{        
    "m_id" : 2,
    "sys_data" : [ 
        {
            "sattr" : {
                "size" : 2,
                "d_data" : [ 
                    {
                        "d_counter" : 2,
                        "client_ip" : "1.1.1.1",
                        "d_date" : "02/01/01"
                    }, 
                    {
                        "d_counter" : 2,
                        "client_ip" : "1.1.1.1",
                        "d_date" : "02/01/01"
                    }, 
                    {
                        "d_counter" : 2,
                        "client_ip" : "1.1.1.1",
                        "d_date" : "03/01/01"
                    }
                ]
            }
        }
    ]
},
{
    "m_id" : 2,
    "sys_data" : [ 
        {
            "sattr" : {
                "size" : 2,
                "d_data" : [ 
                    {
                        "d_counter" : 2,
                        "client_ip" : "1.1.1.1",
                        "d_date" : "02/01/01"
                    }
                ]
            }
        }
    ]
}])

运行汇总管道:

var pipeline = [
    {
        "$match": {
            "sys_data.sattr.d_data.d_date" : "02/01/01"
        }
    },
    {
        "$unwind": "$sys_data"
    },
    {
        "$unwind": "$sys_data.sattr.d_data"
    },
    {
        "$match": {
            "sys_data.sattr.d_data.d_date" : "02/01/01"
        }
    },
    {
        "$group": {
            "_id": null,
            "count": { "$sum": 1 }
        }
    }
];
db.testCollection.aggregate(pipeline);

示例输出:

/* 0 */
{
    "result" : [ 
        {
            "_id" : null,
            "count" : 3
        }
    ],
    "ok" : 1
}