我需要在laravel框架工作中获得以下查询的结果(使用jenssegers库)
db.product.aggregate({ $group : {_id : "$catid", total : { $sum : 1}}},
{$sort:{total:-1}});
Run Code Online (Sandbox Code Playgroud)
我试着这样做
return DB::connection($this - > connection)- >
collection($this - > collection) - > aggregate(
'{ $group : {_id : "$catid", total : { $sum : 1 }}},{$sort:{total:-1}}'');
Run Code Online (Sandbox Code Playgroud)
但它给出的错误如"ErrorException Undefined index:aggregate"需要知道如何使用mongodb"db.collection.aggregate"
我收藏的文件是这样的
{
"_id": ObjectId("5369d68611fe14ddc5f59ff9"),
"sku": 123456,
"productid": 1,
"name": "name1",
"catid": 1
}
Run Code Online (Sandbox Code Playgroud)
您可以通过该raw()函数访问Jenssegers库上的聚合方法.
以下是我使用的工作随机聚合调用示例,您可以根据自己的需要进行调整:
//Perform an aggregate function and get a cursor
$cursor = Data::raw()->aggregate([
['$group' =>
['_id' => '$name', 'count' => ['$sum' => 1]]
],
['$sort' => ['count' => -1]],
['$limit' => 30],
['$project' => ['_id' => 0,
'text' => '$_id',
'size' => '$count',
]
],
]);
//Iterate your cursor
$current = $cursor;
do {
echo $current; //Process each element
} while (!($current = $cursor->next()));
Run Code Online (Sandbox Code Playgroud)
请注意,使用该raw()方法需要使用游标,因为它是一个低级调用.
希望能帮助到你.
| 归档时间: |
|
| 查看次数: |
4308 次 |
| 最近记录: |