Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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'];