neoexpert
neoexpert

Reputation: 474

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.

Upvotes: 3

Views: 3426

Answers (1)

Jeff J
Jeff J

Reputation: 573

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

Upvotes: 7

Related Questions