如何获得mongodb中每个组的最新N个logging?

我有两个城市的条目。 如何获得每个城市最新的3个条目? 喜欢:

City1
logging1
logging2
logging3

城2
logging1
logging2
logging3

请分享帮助
logging1
logging2
logging3

架构:

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个最近的标题

mongoDB 3.2中,你可以通过使用以下forms的聚合查询来执行此操作:

 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,…sorting的所有最近的标题。如果您对使用此结果感到满意,因为您已经在mostRecentTitle的索引0,1和2中得到结果。 其他标题可以在应用程序端简单地忽略。

不过,如果你不开心,就对输出集合“aggr_out”进行更新,并从这个集合中读取数据。 查询是,

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

上面的操作将切分mostRecentTitle数组,使其具有最近三个标题。 做一个阅读这个集合来获得你想要的结果。