I have created a simple chat application node.js with mongodb successfully. When I show the user list I need them to in sorted order as per the recent chat. currently, I am getting the list of users as the added order. Below are my two collections i.e User and Chat:
User: _id,username,password,uniqueId,date
Chat: _id,sender_id(user uniqueId),receiver_id(user uniqueId),message,date
db.getCollection("Chat").aggregate([
{
$match:
{
$or: [
{sender_id: "<login User UniqueId>"},
{reciver_id: "<login User UniqueId>"}
]
}
},
{
$lookup: {
from: "User",
localField: "reciever_id",
foreignField: "uniqueId",
as: "UserChatList"
}
},
{
$project: {
'_id': 1,
'UserChatList.uniqueId' : 1,
'UserChatList.username' : 1,
'sender_id': 1,
'reciever_id': 1,
'message': 1,
'date':1}
},
{ $sort: { 'date': -1 }}
])
What I expected is when I log in with User A it will give me the list of all users with their recent chat order with User A if User A did chat with some users and did not chat with some users so I need the sort as per recent chat and then user added date.