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.