Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB sort the result after limit

is there a way to sort the documents returned from limit? example:

//returns 10 documents:
db.users.find()
.sort({last_online_timestamp:-1})
.limit(10) 

//returns 10 another documents
db.users.find()
.sort({last_online_timestamp:-1})
.limit(10)
.sort({messages_count:1}); 

what I want is to get 10 last logged in users and then sort them by messages count.

like image 536
neoexpert Avatar asked Nov 29 '25 06:11

neoexpert


1 Answers

You can use an aggregate such as

db.users.aggregate([
    {"$sort": {"last_online_timestamp":1}},
    {"$limit": 10},
    {"$sort": {"messages_count": 1}}
])

This will go through stages where the the documents in the collection will be:

  1. Sorted by the last_online_timestamp field in ascending order
  2. Limited to 10 documents
  3. Those 10 documents will be sorted by the messages_count field in ascending order

You may want to change {"$sort": {"last_online_timestamp":1} to {"$sort": {"last_online_timestamp":-1} depending on the actual values of last_online_timestamp

For more information on Mongo aggregation, see https://docs.mongodb.com/manual/aggregation/.

like image 152
Jeff J Avatar answered Nov 30 '25 18:11

Jeff J