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
Post a Comment