mongodb aggregate(group) sub document 问题
伊谢尔伦
伊谢尔伦 2017-04-24 09:13:05
0
2
476

我的数据:

    { 
        "_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 학습자의 빠른 성장을 도와주세요!