如何在 laravel 框架的 mongodb 中执行聚合 [英] How to execute aggregate in mongodb in laravel framework
问题描述
我需要在 laravel 框架中获得以下查询的结果(使用 jensegers 库)
I need to get result of following query in laravel frame work (used jenssegers library)
db.product.aggregate({ $group : {_id : "$catid", total : { $sum : 1}}},
{$sort:{total:-1}});
我试着这样做
return DB::connection($this - > connection)- >
collection($this - > collection) - > aggregate(
'{ $group : {_id : "$catid", total : { $sum : 1 }}},{$sort:{total:-1}}'');
但它给出的错误像 "ErrorException Undefined index: aggregate" 需要知道如何使用 mongodb "db.collection.aggregate"
But it is giving error like "ErrorException Undefined index: aggregate" need to know that how to use mongodb "db.collection.aggregate"
我收藏的文档是这样的
{
"_id": ObjectId("5369d68611fe14ddc5f59ff9"),
"sku": 123456,
"productid": 1,
"name": "name1",
"catid": 1
}
推荐答案
您可以通过 raw()
函数访问 Jenssegers 库上的聚合方法.
You can access the aggregate method on the Jenssegers library via the raw()
function.
这里是一个包含 group、sort、limit 和 project 的聚合调用示例.您可以根据自己的需要进行调整:
Here is an example of an aggregate call with group, sort, limit and project. You can adapt it to your needs:
//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()));
请注意,使用 raw()
方法需要使用游标,因为它是低级调用.
Note that using the raw()
method requires using a cursor because it is a low-level call.
这篇关于如何在 laravel 框架的 mongodb 中执行聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!