We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

MongoDb Aggregations

Documentation is sparse on the aggregation function. I don't know what the array parameters are and keep getting errors with everything I try. I can sucessfully do aggregation from the mongo shell. I just don't know how to translate that into the Phalcon function.

$articles = Article::aggregate(array(...));

Articles looks like:
{
    "title" : "App Envy",
    "description" : "My Top 10 Android Apps",
    "author" : "Joe",
    "date" : ISODate("2013-01-24T08:00:00Z"),
    "last_update" : null,
    "active" : "",
    "category" : "technology",
    "_id" : ObjectId("51021cf9e73c84170d000000"),
    "text" : "Lorem Ipsum ...",
    "last_updated" : ISODate("2013-03-26T04:18:26.622Z")
}

This is my aggregation query in the mongo shell which works:

var results = new Array();
db.articles.aggregate(
  { $project : {
     category: 1,
  } },
  { $group : {
     _id : {category: "$category"},
     id : {$max : "$_id"},
  } 
  }
).result.forEach(function(o) {
    results.push(db.articles.findOne(o.id));
});
results.forEach(printjson);


3.6k
edited Mar '14

Try this:

Article::aggregate(array(
array(
    '$project' => array('category' => 1)
),
array(
    '$group' => array(
        '_id' => array('category' => '$category'),
        'id' => array('$max' => '$_id')
    )
)
));


12.3k


27.8k

Hi,

How do we include a $match?

Thanks!

Try this:

Article::aggregate(array(
array(
   '$project' => array('category' => 1)
),
array(
   '$group' => array(
       '_id' => array('category' => '$category'),
       'id' => array('$max' => '$_id')
   )
)
));


27.8k

resolved the issue.

Article::aggregate(array(
   array(
'$match' => array('keyword' => "matched")
 ),
array(
'$project' => array('category' => 1)
 ),
array(
'$group' => array(
    '_id' => array('category' => '$category'),
    'id' => array('$max' => '$_id')
)
)
));
edited Jan '17

I would like to ask how to add "aggregation options" to the Method::aggregate() method....

I tried doing Method::aggregate(array(AGGREGATION STAGES GOES HERE), array(AGGREGATION OPTIONS GOES HERE)); but it produces an error 'BadMethodCallException' with message 'Wrong number of parameters'.