2014-07-17 3 views
1

각 회사에 도시, 주 (도) 및 국가가 할당되도록 회사 목록이 있다고 가정합니다.국가, 주 및 도시 단위로 집계

3 단계 집계already mentioned here으로 만들 해결책을 찾고 있습니다. 아쉽게도 원시 MongoDB 쿼리를 PHP로 변환 할 수 없습니다.

현재 예외 :

exception: invalid operator '$push' 

데이터베이스 항목 :

{ 
    "_id" : ObjectId("52c85fafc8526a4d0d21e0be"), 
    "city" : "Freiburg", 
    "country" : "DE", 
    "state" : "DE-BW", 
    "_coords" : { 
     "latitude" : 47.9990077, 
     "longitude" : 7.842104299999999 
    } 
} 

출처 :

$collection = $this->getClient()->getCollection('companies'); 

$ops = array(
    array(
    '$group' => array(
     '_id' => array(
     'country' => '$country', 
     'state' => '$state', 
     'city' => '$city' 
     ), 
    ), 
    ), 
    array(
    '$group' => array(
     '_id' => array(
     'country' => '$_id.country', 
     'state' => '$_id.state' 
     ), 
    ), 
    ), 
    array(
    '$group' => array(
     '_id' => array(
     'country' => '$_id.country', 
     'state' => array('$push' => '$_id.state') 
     ), 
    ), 
    ), 
    array(
    '$sort' => array(
     'state' => 1 
    ), 
    ) 
); 

$results = $collection->aggregate($ops); 

예상 결과 :

[ 
    { 
    "country" : "DE", 
     "states" : 
     [  
      { 
       "state" : "DE-BW", 
       "cities" : [ 
        { 
         "city": "Freiburg", 
         "_coords": { 
          "latitude" : 47.9990077, 
          "longitude" : 7.842104299999999 
         } 
        }, 

        ... 

       ] 
      }, 

      ... 

      ] 
    }, 

    ... 

] 

답변

1

원하는 $group 레벨은 여기에 있습니다. 당신을 위해

db.country.aggregate([ 
    { "$group": { 
     "_id": { 
      "country": "$country", 
      "state": "$state" 
     }, 
     "cities": { 
      "$addToSet": { 
       "city": "$city", 
       "_coords": "$_coords" 
      } 
     } 
    }}, 
    { "$group": { 
     "_id": "$_id.country", 
     "states": { 
      "$addToSet": { 
       "state": "$_id.state", 
       "cities": "$cities" 
      } 
     } 
    }}  
]) 

그리고 PHP 표기 : 사람들의 나머지 부분에 대한 기본 JSON 표기법에서

을 :

$collection->aggregate(
    array(
     array(
      '$group' => array(
       '_id' => array(
        'country' => 'country', 
        'state' => '$state' 
       ), 
       '$cities' => array(
        '$addToSet' => array(
         'city' => '$city', 
         '_coords' => '$_coords' 
        ) 
       ) 
      ) 
     ), 
     array(
      '$group' => array(
       '_id' => '$_id.country', 
       'states' => array(
        '$addToSet' => array(
         'state' => '$_id.state', 
         'cities' => '$cities'         
        )    
       )    
      ) 
     ) 
    ) 
); 

를하지만 심각, 방법에 대해 선택적으로 고유성 $addToSet보다는 $push를 사용하여 json_decode을 사용하십시오. JSON은 일반적인 데이터 구조 표현을위한 "링구아 프랑크 (ningua franca)"이며, YAML이나 단순화 된 XML 또는 다른 것들을 손상시키지 않습니다. 이런 일들을 모국어로 번역하는 것이 어렵지 않습니다. 특히 많은 라이브러리가 존재할 때 그렇습니다.

관련 문제