I have a collection of conversations like this:
[
{
title: ...,
members: [...],
messages: [
{ _id: ..., date: ..., text: ... },
{ _id: ..., date: ..., text: ... },
...
]
},
{
title: ...,
members: [...],
messages: []
},
...
]
Some documents has an empty messages array. I need to select a several collections (for one user), but two things:
1) The order of messages must be reversed (or messages must be ordered by date desc, result is the same).
2) The number of messages for each conversation must be limited.
I tried to reverse messages using this query:
db.conversations.aggregate([
{$match: {members: 'someUserId'}}
{$unwind: '$messages'},
{$sort: {'messages.date': -1}},
{$group: {
_id: '$_id',
title: {$first: '$title'},
members: {$first: '$members'},
messages: {$push: '$messages'}
}}
])
But there is two problems again: conversation with no messages are not selected and messages still not limited.
Do you have any ideas, how to solve it? Or how to solve one of this problems? Thanks!