ColonelHedgehog
ColonelHedgehog

Reputation: 460

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

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.

Upvotes: 0

Views: 581

Answers (1)

s7vr
s7vr

Reputation: 75914

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
    }

?>

Upvotes: 1

Related Questions