We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

ODM $sum

Granted I am pretty new MongoDB, I am finding it hard to figure out how to use $sum on a column in a group of documents. My hack is to search-loop-add but I would like to make use of mongo for something as "seemingly" simple as this.

a document object looks like this:


I just want to sum the bytes based on any of the other fields, such as:

          'conditions' => [
              "clientID" => $clientID,
                "logDate" => ['$regex' => "(2017-01)+", '$options' => "g"]


I figured it out on my lonesome :) For those who are looking for the solution,

$bytesCount = YourModel::aggregate(
                       '$match'=> [
                            'clientID' =>"2147483647",
                           'eventID'=> "2017011013"
                        '$group'=> [
                        '_id'=> "bytesCount",
                            'total'=> [
                            '$sum'=> '$bytes'
//send to an array, this took a while to figure out..
$sumObj = $bytesCount->toArray()[0];
echo $sumObj['total'];