We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 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:

"_id":"5917e182a74ad843c90ee325"
"logDate":"2017-01-04T06:11:00Z"
"bytes":753117
"fullTsString":"/9375922947/7b8daa983b98eeb1b452319f85d660b60540fe24-95.ts"
"streamAsset":"7b8daa983b98eeb1b452319f85d660b60540fe24"
"eventID":"2016121002"
"clientID":"9375922947"
"videoDims":"1280x720"

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

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


2.8k
Accepted
answer

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

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