2014-10-06 71 views
-1

的的Fileds我有一个集合像下面MongoDB的。需要计算一个数组

{ _id: 1, zipcode: "63109", students: [ 
        { name: "john", school: 102, age: 10 }, 
        { name: "jess", school: 102, age: 11 }, 
        { name: "jeff", school: 108, age: 15 } 
       ] } 



{ _id: 2, zipcode: "63110", students: [ 
        { name: "ajax", school: 100, age: 7 }, 
        { name: "achilles", school: 100, age: 8 }, 
       ] } 

{ _id: 3, zipcode: "63109", students: [ 
        { school: 100, age: 7 }, 
        { school: 100, age: 8 }, 
       ] } 

{ _id: 4, zipcode: "63109", students: [ 
        { name: "barney", school: 102, age: 7 }, 
        { name: "ruth", school: 102, age: 16 }, 
       ] } 

注:有些文件亘古不变的有场。

我想查找名称字段的计数。 请建议查询在mongo中查找计数

回答

2

您可以使用与$unwind汇总框架来完成此操作。假设你的收藏名称是test

db.test.aggregate(
    {$unwind: '$students'}, 
    {$match:{'students.name':{$exists:1}}}, 
    {$group:{_id: '$students.name', count:{$sum:1}}}, 
    {$project:{tmp:{name:'$_id', count:'$count'}}}, 
    {$group:{_id:'Total Names', total:{$sum:1}, data:{$addToSet:'$tmp'}}} 
) 

希望这是你想要的!

0

在这种情况下,您需要使用聚合框架。

第一个聚合步骤将使用$unwind将数组转换为文档流。

然后,您可以使用$group作为与$sum:1的第二个聚合步骤来获取每个名称的计数。

db.collection.aggregate([  
    { 
     $unwind: "$students" 
    }, 
    { 
     $group: { 
      _id:"$students.name", 
      count: { $sum:1 } 
     } 
    }  
] 
+0

嗨菲利普感谢您的帮助。我尝试根据您的建议我的查询。 db.transactions.aggregate([{ $ 放松: “body.payload.iemRecords” },{ $ 组:{ _id: “$ body.payload.iemRecords.CID”, 计数:{$总和:1} } } ])但是得到像“”异常:字段路径引用的错误必须以'$'('body.payload.iemRecords',' – Aman 2014-10-06 13:38:08

+0

@Aman,作为前缀看看Deepak的答案。 – bigtunacan 2014-10-06 14:02:31

+0

@Aman您在$ unwind中错过了$ -sign,尝试'$ unwind:“$ body.payload.iemRecords”' – Philipp 2014-10-06 14:21:52