2016-06-09 41 views
1

例如,我有这样一个集合:如何获得一次数组的数量?

{"_id": 1, "type": 'A', "data": "asdff"}, 
{"_id": 2, "type": 'B', "data": "fsdfs"}, 
{"_id": 3, "type": 'A', "data": "aesdf"}, 
{"_id": 4, "type": 'C', "data": "sdsdd"}, 

我能得到A型的计数:

db.colA.find({type: 'A'}).count() 

我怎样才能得到类型的数组,例如,A,B,C的计数

db.colA.find({type: {$in: ['A', 'B', 'C']}}).countByType() ?? 

我应该做一个像db.colA.find({type: type}).count()这样的循环吗?

回答

1

为了做到这一点,您需要使用聚合框架。您只需按“类型”输入$group您的文档,然后使用$sum累加器运算符为每个“类型”返回“计数”。

db.colA.aggregate(
    [ 
     { "$match": { "type": { "$in": [ "A", "B", "C" ] } }, 
     { "$group": { 
      "_id": "$type", 
      "count": { "$sum": 1 } 
     }} 
    ] 
) 

当然,你总是可以得到的总数为 “A”, “B”, “C” 使用count()方法:

db.colA.count({ "type": { "$in": [ "A", "B", "C" ] } }) 
1

这个工作对我来说:

db.getCollection('Mytest').aggregate([{ 
      $group: 
      {_id: {"type":"$type"},"count": { $sum: 1 }}}]) 

输出:

{ 
    "_id" : { 
     "type" : "C" 
    }, 
    "count" : 1 
} 


{ 
    "_id" : { 
     "type" : "B" 
    }, 
    "count" : 1 
} 


{ 
    "_id" : { 
     "type" : "A" 
    }, 
    "count" : 2 
}