Mongodb unwind nested documents
aggregation-framework, mongodb, php
Solution
I know that what you're trying to do is possible with MongoDB. The `aggregate()` command can take as many arguments as you need.
In the mongo shell, a command like this
db.collection.aggregate(
{ $project: {
_id: 1,
items: 1
} },
{ $unwind: '$items' },
{ $unwind: '$items.images' }
);
will unwind the `items` subdocument, then the `images` subdocument.
Based on the code in your question, perhaps this will work
$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);
Problem
I have a document in MongoDB and I'm trying to unwind it in PHP. I want to unwind a document that has a subdocument that contains yet anothersubdocument. I was able to do this succesfully if the document only contains strings and numbers, but if it contains another subdocument then I can't get it to work. I get this error: ``` exception: $unwind: value at end of field path must be an array ``` Can you not unwind a subdocument that contains another level of subdocument? If not, how would you go about doing this? Thanks in advance! This is the query: ``` $project = array( '$project' => array( '_id' => 1, 'items' => 1, ) ); $unwind = array( '$unwind' => '$items' ); $query = $mongo->store->aggregate($project,$unwind_items); ``` This is the structure: ``` { "_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", } ```