2013-11-22 190 views
5

我在MongoDB中有一個文檔,我試圖在PHP中展開它。我想展開一個包含其他子文檔的子文檔的文檔。如果文檔只包含字符串和數字,我可以成功完成此操作,但如果它包含另一個子文檔,則無法使其工作。我得到這個錯誤:Mongodb展開嵌套文檔

exception: $unwind: value at end of field path must be an array 

你不能展開包含另一級別的子文檔的子文檔嗎?如果不是,你會如何去做這件事?

在此先感謝!

這是查詢:

$project = array(
       '$project' => array(
        '_id' => 1, 
        'items' => 1, 
       ) 
      ); 

$unwind = array(
       '$unwind' => '$items' 
      ); 


$query = $mongo->store->aggregate($project,$unwind_items); 

這是結構:

{ 
    "_id": { 
     "$oid": "526fdc1fd6b0a8182300009c" 
    }, 
    "items": [ 
       { 
      "quantity": "1", 
      "category_id": { 
       "$oid": "526fdc1fd6b0a81823000029" 
      }, 
      "category": "test", 
      "images": [ 
       { 
        "name": "9by9easy.PNG", 
        "path": "upload_files/nibh-vulputate-mauris-corporation/", 
        "file_path": "upload_files/nibh-vulputate-mauris-corporation/68e7c50bde1476e96ca2461dc553cce5528fb70e41b1f.PNG", 
        "size": 8761 
       }, 
       { 
        "name": "9by9hard.PNG", 
        "path": "upload_files/nibh-vulputate-mauris-corporation/", 
        "file_path": "upload_files/nibh-vulputate-mauris-corporation/8cd2dcf4fcd476262db2eba3fdb2c39a528fb70e42757.PNG", 
        "size": 11506 
       } 
      ], 
      "link": "fghfhfhfg" 
     } 
    ], 
    "name": "Nibh Vulputate Mauris Corporation", 

} 
+0

PS有一個以上的項目。主要的一點是你可以放鬆和有一個子文件的子文檔 –

回答

14

我知道你想要做什麼是可能的MongoDB的。根據需要,aggregate()命令可以採用多個參數。

在蒙戈外殼,這樣的命令

db.collection.aggregate(
    { $project: { 
    _id: 1, 
    items: 1 
    } }, 
    { $unwind: '$items' }, 
    { $unwind: '$items.images' } 
); 

將解開items子文檔時,則images子文檔。

基於對你的問題的代碼,也許這將工作

$project = array(
    '$project' => array(
    '_id' => 1, 
    'items' => 1, 
) 
); 

$unwind_items = array(
    '$unwind' => '$items' 
); 

$unwind_images = array(
    '$unwind' => '$items.images' 
); 


$query = $mongo->store->aggregate($project,$unwind_items,$unwind_images);