之前写的php操作mongodb类中没有实现聚合操作,研究了好久,在命令行下可以正常,但是用php写的结果与命令行不一样,折腾了好久,发现是写法错了,最后在php官网中找到解决办法,之前在网上看到的都是老的mongo操作方法,不是mongodb,看文档真的很重要:
7 aggregate使用,相当于shell里面的”|”
上面的几乎全部可以用aggregate进行查询
与sql对应关系
sql mongodb
WHERE $match //match里面可以用and,or,以及逻辑判断,但是好像不能用where
GROUP BY $group
HAVING $match
SELECT $project
ORDER BY $sort
LIMIT $limit
SUM() $sum
COUNT() $sum
> db.users.aggregate([{$group:{"_id":"$type","hr_count":{"$sum":1}}}]);
{ "_id" : "wn", "hr_count" : 1 }
{ "_id" : "bt", "hr_count" : 3 }
{ "_id" : "ns", "hr_count" : 3 }
{ "_id" : null, "hr_count" : 6 }
>
Php官方文档示例:
mongodb官方关于pipeline的说明:
php使用aggregate操作mongodb进行求和示例:之前一直没写pipeline,把group放到上一层去了,所以一直无法分组,坑。。。<?php
/**
* Created by PhpStorm.
* User: www.hu-rong.com
* Date: 2018/8/12
* Time: 22:10
*/
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$param = [
'aggregate' => 'users',
'pipeline' => [
[
'$match' => [
'price' => ['$gte' => 3600]
]
],
[
'$group' => [
'_id' => '$type',
'hr_count' => [
'$sum' => 1
]
]
]
],
];
$cmd = new MongoDB\Driver\Command($param);
//print_r($cmd);
print_r($manager->executeCommand('linux_hurong', $cmd)->toArray());
结果:
Array
(
[0] => stdClass Object
(
[waitedMS] => 0
[result] => Array
(
[0] => stdClass Object
(
[_id] => bt
[hr_count] => 2
)
[1] => stdClass Object
(
[_id] => ns
[hr_count] => 1
)
)
[ok] => 1
)
)