Reputation: 77
I'm creating a chat app using MongoDB. Basically I need to retrieve the latest 20 chat messages and then display them by ascending date. In order to get the 20 last chat messages my code looks something like this:
db.messages.find().sort({$date:-1}).limit(20)
but this leaves the messages in reverse order.
Is there a way to do this in a single query? I know this is incorrect but something like db.messages.find().sort({$date:-1}).limit(20).sort({$date:1})
?
Upvotes: 3
Views: 499
Reputation: 2528
Please see this answer: https://stackoverflow.com/a/72860162/8808983
Python:
MAX_DOCS_TO_PROCESS = 3
filter = {} # can be anything
result_cursor = collection_name.find(filter).sort("timestamp", pymongo.DESCENDING).limit(MAX_DOCS_TO_PROCESS)
# Here the cursor will give:
# [{_id: 100, timestamp: 100}, {_id: 99, timestamp: 99}, {_id: 98, timestamp: 98}]
result_list = sorted(result_cursor, key=lambda doc: doc.get("timestamp", 0))
# Here the list will be:
# [{_id: 98, timestamp: 98}, {_id: 99, timestamp: 99}, {_id: 100, timestamp: 100}]
Upvotes: 0
Reputation: 1164
Because the sort and limit commands are actually modifications to the query that gets sent to the mongod server, there isn't a way to easily attach two sorts to a single query command. You could do this in mongodb using the aggregation framework, but that wouldn't be a good solution for such a small use case...
In this case, your best bet is probably to just reverse the results in your application code. In fact, mongodb is designed with the idea that the client should handle most data manipulation of this kind. I'm not sure what language you're using, but most have a way to reverse an array or iterate through a list backwards--that should work just fine here.
Upvotes: 2