2014-05-08 60 views
6

我需要在laravel工作框架下面的查詢結果(使用jenssegers庫)
如何在MongoDB中的laravel框架執行總

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」

我收藏的文件是這樣的

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

如果可能的話顯示你的數據庫結構的問題 – Mayuri

+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

嘗試這樣的事情

db.product.aggregate(
    { "$group" : 
     { "_id" : "$catid", 
      "total" : { "$sum" : 1} 
     } 
    }, 
    { "$sort" : {"productid":-1} } 
); 
+3

感謝您的想法,但我需要使用laravel框架工作來執行此查詢。我使用jenssegers庫作爲db連接器 –