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

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
user1457750
  • 53
  • 1
  • 2
  • 4

2 Answers2

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')  
                                )
                            )
                    )
            )
        );
William Z
  • 10,989
  • 4
  • 31
  • 25
  • 2
    An [aggregate()](http://php.net/manual/en/mongocollection.aggregate.php) helper has been added in the 1.3.0 `mongo` driver. The underlying `command()` syntax still works, too :). – Stennie Sep 22 '12 at 22:51
  • I also tried like this for my query. But it is returning an error which says exception: wrong type for field (aggregate) 3 != 2 – Happy Coder Nov 15 '13 at 10:39
  • @Alwin: this means that you have a syntax error. There's no way to know what it is without seeing your code. – William Z Nov 15 '13 at 14:25
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

Indrajeet Singh
  • 2,958
  • 25
  • 25