每个城市我都有几个条目。如何获取每个城市的最新 3 个条目?喜欢:
城市1
记录1
记录2
记录 3
城市2
记录1
记录2
记录 3
城市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 个最新标题
最佳答案
在 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 排序,...如果您对使用此结果感到满意,因为您已经在 mostRecentTitle 的索引 0、1 和 2 中获得结果.其他标题在应用端可以简单忽略。
如果您不满意,请对输出集合“aggr_out”进行更新,并从该集合中读取数据。查询是,
db.aggr_out.update(
{},
{$push: {
mostRecentTitle: {$each:[], $slice:3}
}
}
)
上述操作将切片 mostRecentTitle 数组,以便它具有最近的三个标题。阅读此系列以获得您想要的结果。
关于node.js - 如何在mongodb中获取每个组的最新N条记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34325714/