MongoDB查询用PHP中的聚合获取数据

时间:2017-11-24 11:18:21

标签: php mongodb mongodb-query cloud aggregation-framework

$filter = array();
$options = array("sort" => array("age" => -1));
$query = new \MongoDB\Driver\Query($filter, $options);

这种类型的方法适用于mongo查询,如db.collection.find({age:-1}),但是我想让方法像下面那样运行聚合查询以在PHP中运行并获取var_dump中的数据?所以我可以在我的PHP中使用数据。

问题:如果我想在我的PHP中运行这样的聚合查询以获取数据,该怎么办?

db.catalog.aggregate(
    [     
    {$unwind: '$productOrdered'},
    {$group: {_id: '$productID', 'totalOrdered': { $sum: 1}}} 
    ]
    ); 

==================>获取产品的购买次数

集合看起来像

-productID,

-productName,

-productOrdered{

    customerID,

    dateofpurchse,

}

以前我使用的方法如下所示,在localhost中工作得很好,但是当我在CLOUD中上传时它不起作用,所以让我改变其他方法,也许就像上面一样。如果我可以在云中运行,我会坚持这一点。 - AliCloud

<?php
$m = new MongoClient("localhost");

$c = $m->selectDB("examples")->selectCollection("article");

$data = array (
   'title' => 'this is my title',
   'author' => 'bob',
   'posted' => new MongoDate,
   'pageViews' => 5,
   'tags' => array ( 'fun', 'good', 'fun' ),
   'comments' => array (
     array (
       'author' => 'joe',
       'text' => 'this is cool',
       ),
     array (
       'author' => 'sam',
       'text' => 'this is bad',
       ),
     ),
   'other' =>array (
     'foo' => 5,
     ),
   );
$d = $c->insert($data, array("w" => 1));

$ops = array(
   array(
    '$project' => array(
        "author" => 1,
        "tags"   => 1,
        )
    ),
   array('$unwind' => '$tags'),
   array(
    '$group' => array(
        "_id" => array("tags" => '$tags'),
        "authors" => array('$addToSet' => '$author'),
        ),
    ),
   );

$results = $c->aggregate($ops);
var_dump($results);
?>

0 个答案:

没有答案