2016-12-02 52 views
-1

我有我的收藏数集合中的特定领域的occurence数:如下图所示如何在MongoDB中

{ 
    "_id" : NumberLong(366), 
    "file" : "xyz", 
    "clist" : { 
        "account" : "BFS", 
        "subAccount":"a" 
       }, 
}, 
{ 
    "_id" : NumberLong(366), 
    "file" : "xyz", 
    "clist" : { 
        "account" : "BFS", 
        "subAccount":"b" 
       }, 
}, 
{ 
    "_id" : NumberLong(366), 
    "file" : "xyz", 
    "clist" : { 
        "account" : "HC", 
        "subAccount":"c" 
       }, 
} 

在,我要通过组账号和计数子账户的数量;例如:

{ 
    account : "BFS", 
    subAccount : "b", 
    count : 1, 
    subAccount :"a", 
    count : 1 
} 

如果帐户BFS,子账户b存在两次的话,我应该得到的输出是这样的:

{ 
    account : "BFS", 
    subAccount : "b", 
    count : 2, 
    subAccount : "a", 
    count : 1 
} 
+0

是'clist'你的mongo文件? – nullpointer

+0

嗨克里希纳;我编辑了你的问题,使预期的输出更具可读性。这不是批评;在这个网站上,每个人都被鼓励合作,编辑问题以进一步改进。如果您可以添加更多信息,请再次编辑该问题以澄清。 –

回答

0

愿这帮助你...

db.coll.aggregate([ { 
    "$group" : { 
     "_id" : { 
      "account" : "$clist.account", 
      "subAccount" : "$clist.subAccount" 
     }, 
     "count" : { 
      "$sum" : 1 
     } 
    } 
}, { 
    $project : { 
     _id : 0, 
     "account" : "$_id.account", 
     "subAccount" : "$_id.subAccount", 
     "count" : "$count" 
    } 
}, { 
    $group : { 
     _id : "$account", 
     "subaccounts" : { 
      "$push" : { 
       "subAccount" : "$subAccount", 
       "count" : "$count" 
      } 
     } 
    } 
} ])