How to get the last N entries of each group in mongodb?

I have a couple entries for each city. How to get the last 3 entries in each city? How:

City1
record 1
record 2
record 3

City2
record 1
record 2
record 3

City3
record 1
record 2
record 3

Scheme:

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

The code I tried:

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

So, how to fulfill the query, where should I have the result: 3 most recent headings of each city

+4
source share
1 answer

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, . , .

+4

Source: https://habr.com/ru/post/1620459/


All Articles