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.
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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With