Mongodb展开嵌套文档

时间:2013-11-22 20:47:24

标签: php mongodb aggregation-framework

我在MongoDB中有一个文档,我试图在PHP中解开它。我想展开一个文档,其中包含一个包含anothersubdocument的子文档。如果文档只包含字符串和数字,我能够成功地执行此操作,但如果它包含另一个子文档,那么我无法使其工作。我收到这个错误:

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",

}

1 个答案:

答案 0 :(得分:14)

我知道你可以用MongoDB做的事情。 aggregate()命令可以根据需要使用尽可能多的参数。

在mongo shell中,有一个像这样的命令

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