2014-07-17 181 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水平在这里。可选择使用$addToSet而不是$push的唯一性:

在基本JSON对象为人们的休息:

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符号为您提供:

$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'         
        )    
       )    
      ) 
     ) 
    ) 
); 

但严重的是,学会如何使用json_decode。 JSON几乎是用于一般数据结构表示的“通用语言”,不是为了减损YAML或简化的XML或其他。把这些东西翻译成母语代表并不难,特别是当许多图书馆存在这样做时。