如何在laravel框架中的mongodb中执行聚合

时间:2014-05-08 06:52:56

标签: mongodb laravel-4

我需要在laravel框架工作中获得以下查询的结果(使用jenssegers库)

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”

我收藏的文件就像这样

  {
     "_id": ObjectId("5369d68611fe14ddc5f59ff9"),
     "sku": 123456,
     "productid": 1,
     "name": "name1",
     "catid": 1
 }

2 个答案:

答案 0 :(得分:5)

您可以通过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()));

请注意,使用raw()方法需要使用游标,因为它是一个低级别的调用。

希望它有所帮助。

答案 1 :(得分:-1)

尝试这样的事情

db.product.aggregate(
     { "$group" : 
        { "_id" : "$catid", 
          "total" : { "$sum" : 1}
        }
     },
     { "$sort" : {"productid":-1} }
);
相关问题