1

My collection schema are as follows

Schema: Users

users: [
  {
    id: 1234,
    username: 'someuser'
  }
];

Schema: Messages

messages: [
  {
    id: 1,
    sender_id: <user_id>,
    receiver_id: <user_id>,
    text: 'some message',
    created_at: <timestamp>
  }
];

I need all users list with their last message with timestamps. The list of the users should be sorted by last messages' timestamp.

I tried the following code.

db.users.aggregate([
{
    $lookup: {
       from: 'messages',
       localField: '_id',
       foreignField: ['sender_id', 'receiver_id'], // user id could either be sender id or receiver id. but this field expecting string instead of an array,
       as: 'message' // I am expecting single object of message instead collection of messages,
    }
},
{
    $sort: {
        'message.created_at': -1
    }
}
])

I know it could be done easily using rdms. I hope mongodb is lot better than I am thinking.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Md Adil
  • 307
  • 1
  • 11
  • I didn't understand how this question is duplicate? I just need all users list with their last message with timestamps. The list of the users should be sorted by last messages' timestamp. – Md Adil Mar 21 '17 at 11:11
  • M. Styvane Soukossi, chridam! Can you please help to get the results, still I am not able to get the required results. – Md Adil Mar 21 '17 at 12:06

0 Answers0