mongodb模糊查询 php7_php7中使用mongodb的aggregate进行聚合操作(sum求和,avg等)

之前写的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

)

)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值