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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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 php.net/manual/en/function.array-sum.php
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?
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)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.