如何在Laravel框架中的MongoDB中执行聚合 [英] How to execute aggregate in mongodb in laravel framework
问题描述
我需要在laravel框架(使用的jenssegers库)中获取以下查询的结果
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未定义索引:聚合"之类的错误,需要知道如何使用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.
这里是我使用的工作随机聚合调用的示例,您可以根据需要进行调整:
Here is a sample of a working random aggregate call that I use, 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屋!