mongodb aggregation php

2019-01-24 18:49发布

问题:

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

回答1:

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')  
                                )
                            )
                    )
            )
        );


回答2:

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