0

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.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Tushar
  • 1
  • 1
  • See this: [https://stackoverflow.com/a/58321949/3710490](https://stackoverflow.com/a/58321949/3710490) – Valijon Oct 13 '19 at 08:08
  • Thanks, Valijon. Now I get the recent chat user but I want to join my user table so the final list I need is recent chat users and then append users from user collection(which did not chat yet) – Tushar Oct 14 '19 at 09:10

0 Answers0