2

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!

1 Answer 1

2

There is a sort and slice operator that can be used in conjunction when you push the messages into the document arrays:

http://docs.mongodb.org/manual/reference/operator/sort/ http://docs.mongodb.org/manual/reference/operator/slice/

They keep your array sorted and limited respectively.

1
  • Thanks, Dylan! But all of messages must be stored in database. Limit must be a parameter when history is loading.
    – Johan
    Commented Jul 24, 2013 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.