laravel 4 - Multi-level sum in mongoDb -


i working on mongodb laravel using jenssegers. , trying sum based on time.estimated_time_in_number.

i have mongodb document contains following data.

"time": [      {        "id": "qzmv154213",        "estimated_time_in_number": 4.41     },     {        "id": "qzmv154213",        "estimated_time_in_number": 2.25     },{        "id": "qzmv154213",        "estimated_time_in_number": 5     }   ] 

i using following query , gives me 0 rather 11.66.

task::sum('time.estimated_time_in_number'); 

you use aggregation framework sum , aggregation pipeline gives result this:

db.task.aggregate([     {         "$unwind": "$time"     },     {         "$group": {             "_id": 0,             "total_estimated_time": {                 "$sum": "$time.estimated_time_in_number"             }         }     } ]) 

which give output

/* 0 */ {     "result" : [          {             "_id" : 0,             "total_estimated_time" : 11.66         }     ],     "ok" : 1 } 

to implement in laravel, use raw query follows uses underlying mongodb aggregation framework above , faster, more efficient out of native framework interface:

task::raw(function($collection){                return $collection->aggregate(array(                    array('$unwind' => '$time'),                                       array('$group' => array(                        "_id" => 0,                        "total_estimated_time" => array('$sum' => '$time.estimated_time_in_number')                    )),                ));             }); 

-- update --

you assign variable result mongodb aggregation query follows:

$result = db::collection('tasks')->raw(function($collection) {     return $collection->aggregate(array(            array('$unwind' => '$time'),                               array('$group' => array(                "_id" => 0,                "total_estimated_time" => array('$sum' => '$time.estimated_time_in_number')            )),       ));  });  

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -