Mukesh Yadav
Mukesh Yadav

Reputation: 2386

Aggregate pipeline with $match not working in php mongo

I want to aggregate a field with matching value.

So far I have following Query

array(
'aggregate' => wines,
'pipeline'=>
    array(                              
        array(
            '$group' => array(
                '_id' => array('name' => '$name', "winery" => $winery )
            )                                   
        ),
        array(
            '$group' => array(
                '_id' => $_id.winery,
                'count' => array('$sum' => 1)
            )
        )

    ),
    '$match' => array('wine_type'=>'red wine')
);

The above query gives aggregated wines but it does not filters Red wine.

Note: I run this in command function.

Upvotes: 1

Views: 2737

Answers (2)

Sammaye
Sammaye

Reputation: 43884

The reason is that the field doesn't exist by the end of the aggregation due to the multiple group. This is since the result of one pipeline is passed to the other, so in fact you are searching for a field of wine_type while there is only _id and count.

Also you have a syntax error, the $match is on the wrong level.

You can put the $match at the beginning or you can add the field to the list of projected group fields in your aggregation.

Upvotes: 0

Neil Lunn
Neil Lunn

Reputation: 151112

Not very clear in your question, but you appear to have $match in the wrong place:

array(
    'aggregate' => wines,
    'pipeline'=>
        array(                              
            array(
               '$match' => array('wine_type'=>'red wine')
            ),
            array(
                '$group' => array(
                    '_id' => array('name' => '$name', "winery" => $winery )
                 )                                  
            ),
            array(
                '$group' => array(
                    '_id' => $_id.winery,
                    count' => array('$sum' => 1)
                )
            )
        )
    )
);

You should get used to the standard invocation of aggregate rather than the runCommand form. Future releases will return a cursor for the result.

Upvotes: 4

Related Questions