2

I am new in mongodb working on to develop chat application,

from two collections I want result with fields names like _id, username, fname, lname, isOnline, updatedAt, count. _id,username,fname,lname,isOnline and updatedAt comes under users collection and count which I have to obtain based on, _id(sender_id) and active_user(which I pass from function when user gets online, its receiverId) having isRead=false.

Users collection fields are, enter image description here

Chat collection fields are, enter image description here

here User devanggarach is online, I wanted to get list of users with count of unread messages(isRead=false)

enter image description here

devanggarach
  • 184
  • 2
  • 13

1 Answers1

1
db.users.aggregate(
    [
            {
            $lookup:{
                        from:"chats",
                        localField : "_id",
                        foreignField : "receiverId",
                        as : "data"
                    }
             },
             {
                $unwind:"$data"
             },
             {
                $match:{
                        "data.isRead":false,
                        _id:{
                                $ne:ObjectId("ID")
                            }
                      }
             },
             {
             $group:{
                        _id:"$_id",
                        username:{$first:"$username"},
                        fname:{$first:"$fname"},
                        lname:{$first:"$lname"},
                        isOnline:{$first:"$isOnline"},
                        updatedAt:{$first:"$updatedAt"},
                        unRead:{$sum:1}
                    }
             },
             {
                $project:{
                            _id:1, username:1, fname:1, lname:1, isOnline:1, updatedAt:1, unRead:1
                         }
             }
    ]
).pretty()