简体   繁体   English

如何在Mongodb中使用聚合函数?

[英]How to use aggregate function in Mongodb?

I have upgraded php5 to php7. 我已经将php5升级到php7。 If I use mongoClient for mongodb connection it shows error.So I used following command. 如果我使用mongoClient进行mongodb连接,则会显示错误,因此我使用了以下命令。

$manager = new MongoDB\\Driver\\Manager("mongodb://".MONGOHOST.":27017");

By using above command I can able to connect db.Now problem is In php5, I used aggregate function.It doesn't support in php7. 通过使用上面的命令,我可以连接数据库了。现在的问题是在php5中,我使用了聚合函数,但在php7中不支持。 Code used in php5 mentioned below.. 下面提到的php5中使用的代码。

for db connection 用于数据库连接

$m = new MongoClient('mongodb://'.MONGOHOST.'', array('username' => MONGOUSER, 'password' => MONGOPASS, 'db'=> MONGODB )); $db = $m->selectDB(MONGODB);

to retrieve value from db: 从数据库检索值:

$ops = array(
        array(
             '$match'=>array(
                "datetime"=>array('$gte'=>$start,'$lte'=>$end)
                )
            ),
        array(
            '$group' => array(
                "_id" => array("slotid" => '$slotid',"bidder" => '$bidder',"viewerid" => '$viewerid',"mediatype"=>'$mediatype'),"total" => array('$sum' => 1),"sitename" =>array('$addToSet' => '$sitename'),"aid" =>array('$addToSet' => '$accountid'),
                ),
            ),
        );

$reqbids = $db->requestbids->aggregate($ops); $ reqbids = $ db-> requestbids-> aggregate($ ops);

How to do this is using mongo driver..I have searching 2 days,but didn't find the solution. 我正在搜索2天,但没有找到解决方案。

You can't use mongoClient. 您不能使用mongoClient。
You have to use Mongodb manager 您必须使用Mongodb Manager
http://php.net/manual/en/class.mongodb-driver-manager.php http://php.net/manual/zh/class.mongodb-driver-manager.php

and for aggregate function use following code. 对于聚合函数,请使用以下代码。 Link 链接
$conn = new MongoDB\\Driver\\Manager("mongodb://127.0.0.1");

$command = new MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => [
        ['$group' => ['_id' => '$y', 'sum' => ['$sum' => '$x']]],
    ],
    'cursor' => new stdClass,
]);
$cursor = $manager->executeCommand('db', $command);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM