Using “aggregate” to combine a list of all subdocuments that match query?

纵饮孤独 提交于 2020-01-07 03:26:26

问题


I'm trying to use a PHP mongo library to "aggregate" on a data structure like this:

{
    "_id": 100,
    "name": "Joe",
    "pets":[
        {
            "name": "Kill me",
            "animal": "Frog"
        },
        {
            "name": "Petrov",
            "animal": "Cat"
        },
        {
            "name": "Joe",
            "animal": "Frog"
        }
    ]
},
{
    "_id": 101,
    "name": "Jane",
    "pets":[
        {
            "name": "James",
            "animal": "Hedgehog"
        },
        {
            "name": "Franklin",
            "animal": "Frog"
        }
}

For example, if I want to get all subdocuments where the animal is a frog. Note that I do NOT want all matching "super-documents" (i.e. the ones with _id). I want to get an ARRAY that looks like this:

    [
        {
            "name": "Kill me",
            "animal": "Frog"
        },
        {
            "name": "Joe",
            "animal": "Frog"
        },
        {
            "name": "Franklin",
            "animal": "Frog"
        }
     ]

What syntax am I supposed to use (in PHP) to accomplish this? I know it has to do with aggregate, but I couldn't find anything that matches this specific scenario.


回答1:


You can use below aggregation. $match to find documents where array has a value of Frog and $unwind the pets array. $match where document has Frog and final step is to group the matching documents into array.

<?php

    $mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    $pipeline = 
        [
            [   
                '$match' => 
                    [
                        'pets.animal' => 'Frog',
                    ],
            ],
            [   
                '$unwind' =>'$pets',
            ],
            [   
                '$match' => 
                    [
                        'pets.animal' => 'Frog',
                    ],
            ],
            [
                '$group' => 
                    [
                        '_id' => null,
                        'animals' => ['$push' => '$pets'],
                    ],
            ],
        ];

    $command = new \MongoDB\Driver\Command([
        'aggregate' => 'insert_collection_name', 
        'pipeline' => $pipeline
    ]);

    $cursor = $mongo->executeCommand('insert_db_name', $command);

    foreach($cursor as $key => $document) {
            //do something
    }

?>


来源:https://stackoverflow.com/questions/42044155/using-aggregate-to-combine-a-list-of-all-subdocuments-that-match-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!