Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB query to distinct, sort, limit and offset

Tags:

sql

mongodb

I'm looking for a Mongo equivalent of the following:

select distinct event_type_id from events
order by created_at desc
limit 10,20

The Event Mongo document is as follows:

{
  _id: BSON(), event_type_id: 1, created_at: Date(), other_data: {}
}
like image 436
Sohan Avatar asked Jan 10 '13 21:01

Sohan


1 Answers

You can use Aggregation Framework on new mongo versions. Here is the example to start from:

db.events.aggregate([
    {$sort:{"created_at":-1}},
    {$project:{"event_type_id":1}},
    {$group:{"_id":"$event_type_id"}},
    {$skip:10},
    {$limit:20}
])

Here is another approach, thanks to @JoachimIsaksson

db.events.aggregate([
    {$group:{"_id":"$event_type_id", "created_at":{$max:"$created_at"}}},
    {$sort:{"created_at":-1}},
    {$skip:10},
    {$limit:20},
    {$project:{"event_type_id":1}}
])
like image 61
madhead - StandWithUkraine Avatar answered Sep 27 '22 23:09

madhead - StandWithUkraine