In mongoDB 3.2, you can accomplish this using an aggregate query of the following form:
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
Query:
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 mostRecentTitle, .
, , 'aggr_out' . :
db.aggr_out.update(
{},
{$push: {
mostRecentTitle: {$each:[], $slice:3}
}
}
)
mostRecentTitle, . , .