2015-12-17 157 views
4

我有兩個城市的條目。如何獲得每個城市最新的3個條目?像:如何獲得mongodb中每個組的最新N個記錄?

City1
記錄1
記錄2
記錄3

城2
記錄1
記錄2
記錄3

請分享幫助
記錄1
記錄2
記錄3

的模式:

var schema = mongoose.Schema({ 
    city: {type: String}, 
    title: {type: String}, 
    created: {type: Number, default: Math.floor(new Date()/1000)} 
}) 

我已經試過代碼:

Collection 
.find('location $in ' + cities) 
.aggregate({$group: {location: "$location"}}) 
.sort('created: 1') 
.limit(3).exec(function(err, docs) { res.render('index', { hash: docs }); }); 

那麼,如何執行查詢,我應該有作爲的結果:3個最近的標題每個城市的

+0

它已被標記,但要清楚:您正在使用貓鼬,對不對? – markthethomas

+0

也是,你想要返回一組或多組?另一個解釋是:這些城市中的每一個都是他們自己的收藏品,個別物品還是什麼? – markthethomas

+0

是的,對!我正在使用貓鼬。 –

回答

4

mongoDB 3.2您可以通過使用以下形式的聚合查詢來執行此操作:

db.collection.aggregate(
    {$sort: {created: -1}}, 
    {$group: {_id:'$city', title:{$push: '$title'}}, 
    {$project: {_id:0, city: '$_id', mostRecentTitle: {$slice: ['$title', 0, 2]}}} 
) 

使用mongoDB 3.0很難達到同樣的效果。一個非常骯髒的技巧是在3.0中實現這一點。它涉及幾個步驟和其他收集。

首先做一個彙總,並將結果輸出到名爲「aggr_out」

查詢的臨時集合:

db.collection.aggregate([ 
    {$sort: {created: -1}}, 
    {$group: {_id:'$city', title:{$push: '$title'}}, 
    {$project: {city: '$_id', mostRecentTitle: '$title'}}, 
    {$out: 'aggr_out'}] 
) 

使用上面的查詢,mostRecentTitle將所有索引0下令近期標題,1,2,...如果你對這個結果很滿意,使用這個結果,因爲你已經在最新的標題的索引0,1和2中得到了結果。其他標題可以在應用程序方面簡單地忽略。

如果您不滿意,請對輸出集合「aggr_out」進行更新,然後從該集合中讀取數據。該查詢,

db.aggr_out.update(
    {}, 
    {$push: { 
    mostRecentTitle: {$each:[], $slice:3} 
    } 
    } 
) 

上述操作將切片mostRecentTitle陣列,使其具有最近三個冠軍。做一個閱讀這個集合來獲得你想要的結果。

+0

我得到了這個錯誤「無法識別的管道階段名稱$項目」 –

+0

{[MongoError:例外:無效的操作符'$切片'] ..} –

+0

您如何提到,沒有mongodb 3.0.x版是我的。也許我可以找到另一種片段。 –

相關問題