0

I am trying to write a PHP (Mongo) query from SQL in which I have SUM() but I am not sure my syntax is correct. Can someone enlighten me?

SQL:

$cmd = "SELECT SUM(m_length) FROM pkt_tbl WHERE m_time>=" . $time. " AND m_buffer_latency<=" . $time;

Mongodb Query:

    $find_projection= aggregate(array('$group'=>array('$sum'=>'$m_length')));
    $result = $table -> command($find_projection);

Can I use array_sum is the $result or is there anyway I can use $SUM (Aggregate) in this case. Any help would be appreciated.

Thanks

iron man
  • 41
  • 8

2 Answers2

3

You should try aggregation

In php this code may help you,

<?php
    $m = new Mongo;
    $c = $m->selectDB("test")->selectCollection("zips");

    $out = $c->aggregate(array(
            '$group' => array(
                '_id' => '$state',
               'totalPop' => array('$sum' => '$pop')
            )
        ),
        array(
            '$match' => array('totalPop' => array('$gte' => 10*1000*1000))
        )
    );

    var_dump($out);
?>

Mongocollection Aggregate

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • Thanks for your inputs. Any suggestions regarding my query would be appreciated. Can you check my query? I used array_sum in $result, can I implement like that? – iron man Jul 19 '13 at 04:54
  • `array_sum` gets an `array as a parameter` to `calculate the sum` like `array_sum(array(2,4,8,6));` but check what are you passing in it? Passing `array('m_length' => 1)` to `array_sum` makeing some sense? Read this http://php.net/manual/en/function.array-sum.php – Rohan Kumar Jul 19 '13 at 04:58
  • hmm I thought passing `$find_projection` which is `array('m_length'=>1` would be considered an array(since it's array()) . can you enlighten me as to how to change my query then? – iron man Jul 19 '13 at 05:06
  • Read this http://stackoverflow.com/questions/8874671/taking-sum-of-column-in-mongodb and http://docs.mongodb.org/manual/reference/method/db.collection.group/ it may help you. – Rohan Kumar Jul 19 '13 at 05:13
  • Alright. I have tried to use aggregate, Still am not getting the issue. Can someone check my syntax? `$find_projection= aggregate(array('$group'=>array('$sum'=>'$m_length')));` `$result = $table -> command($find_projection)` – iron man Jul 19 '13 at 18:15
0
$result = $table->aggregate(
array('$match' => array(
'm_time' => array('$gte' => $max),
'm_buffer_latency' => array('$lte' => $max),
)),
array('$group' => array(
'_id' => true,
'sum_length' => array('$sum' => '$m_length')
))
); 

This answers it all

iron man
  • 41
  • 8