mongodb aggregate(group) sub document 問題
伊谢尔伦
伊谢尔伦 2017-04-24 09:13:05
0
2
474

我的數據:

    { 
        "_id" : ObjectId("542911f4d7054ab6ee0de476"), 
        "name" : "policy2", 
        "url" : [ "www.url22.com", "www.url21.com" ], 
        "countries" : [ 
            { "country" : "USA" }, 
            { "country" : "GER" } 
        ] 
    }

我想單獨group by countries.country字段,單獨統計USA出現幾次,China出現幾次,而不是[USA,GER]在一起出現幾次,如下:

{ "_id" : "China", "total" : 1 }
{ "_id" : "USA", "total" : 2 }
{ "_id" : "GER", "total" : 1 }
{ "_id" : "JP", "total" : 1 }

我嘗試使用aggregate

db.policy.aggregate({$group:{_id:"$countries.country",total:{$sum:1}}})

但是得到的結果是countries合在一起的統計結果:

{ "_id" : [ "China" ], "total" : 1 }
{ "_id" : [ "USA", "JP" ], "total" : 1 }
{ "_id" : [ "USA", "GER" ], "total" : 1 }

求解決方案! !

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回覆(2)
洪涛

使用 $unwind:

db.policy.aggregate([ 
  { $unwind: '$countries' },
  { $group: { _id: '$countries.country', total: { $sum: 1 } } }
]);
Peter_Zhu

我找到解决方案了原来是使用$unwind函数

> db.policy.aggregate([{$unwind:"$country"},{$group:{_id:"$country",total:{$sum:1}}}])
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!