每个城市都有几个条目。如何获得每个城市的最新3个条目?喜欢:
City1
记录1
记录2
记录3
City2
记录1
记录2
记录3
City3
记录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数组进行切片,使其具有最新的三个标题。阅读此收藏以获得所需的结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句