Reputation: 474
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
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:
last_online_timestamp
field in ascending ordermessages_count
field in ascending orderYou 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