$data = MongoDbModelName::getCollection()->aggregate([
[
'$group' => [
'_id' => '$user_id', //通过user_id分组去重
'total' => [
'$sum' => 1
]
],
],
[
'$match' => [
'total' => [
'$gt' => 1
]
]
]
],['allowDiskUse' => true]);
相当于
select user_id,count(1) as total from MongoDbCollection group by user_id having count(1) > 1
aggregate的第二个参数['allowDiskUse' => true]
,是表示允许使用内存,比如数据量大的时候,可以加上这个;如果数据量小的话,这个参数可以直接去掉。 如果需要按两个字段进行分组的话,可以将 $group 的_id指定为数组,如下:
$data = MongoDbModelName::getCollection()->aggregate([
[
'$group' => [
'_id' => ["aid":"$aid","user_id":"$user_id"], //通过aid和user_id分组
'total' => [
'$sum' => 1
]
],
],
[
'$match' => [
'total' => [
'$gt' => 1
]
]
]
],['allowDiskUse' => true]);
相当于文章来源:https://www.toymoban.com/news/detail-651235.html
select aid,user_id,count(1) as total from MongoDbCollection group by aid,user_id having count(1) > 1
如果要限制输出条数。可以在aggregate
的第一个参数数组尾部中增加["$limit" => 1]
,必须是尾部,因为aggregate的会使用第一个参数的元素进行过滤,第一个元素过滤后的结果会给第二个元素,依次内推;实例如下文章来源地址https://www.toymoban.com/news/detail-651235.html
$data = MongoDbModelName::getCollection()->aggregate([
[
'$group' => [
'_id' => ["aid":"$aid","user_id":"$user_id"], //通过aid和user_id分组
'total' => [
'$sum' => 1
]
],
],
[
'$match' => [
'total' => [
'$gt' => 1
]
]
],
[
'$limite' => 15
]
],['allowDiskUse' => true]);
到了这里,关于Yii2 mongodb分组查询的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!