4

I'm using mongodb 2.1 and how to translate this query into php

db.counter.aggregate([ 
 { $match:{ page_id:123456 }}, 
 { $group:{_id:"$page_id",total:{$sum:"$pageview"}} } 
 ]);

Thanks

0

2 Answers 2

16

You can use the 'command()' method in PHP to run the aggregation framework as a database command. The precise syntax for your sample query would be:

   $conn = new Mongo("localhost:$port");
   $db = $conn->test;

   $result = $db->command (
            array( 
                "aggregate" => "counter",
                "pipeline" => 
                    array( 
                        array( '$match' => array( 'page_id' => 123456 )),
                        array( '$group' => array( "_id" => '$page_id',
                                    'total' => array( '$sum' => '$pageview')  
                                )
                            )
                    )
            )
        );
Sign up to request clarification or add additional context in comments.

3 Comments

An aggregate() helper has been added in the 1.3.0 mongo driver. The underlying command() syntax still works, too :).
I also tried like this for my query. But it is returning an error which says exception: wrong type for field (aggregate) 3 != 2
@Alwin: this means that you have a syntax error. There's no way to know what it is without seeing your code.
0

Try:

$m = new MongoClient();
$con = $m->selectDB("dbName")->selectCollection("counter");
$cond = array(
    array('$match' => array('page_id' =>123456)),
    array(
        '$group' => array(
            '_id' => '$page_id',
           'total' => array('$sum' => '$pageview'),
        ),
    )
);
$out = $con->aggregate($cond);
print_r($out);

For more detail click here

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.