'Get last conversations as admin in mongodb

I have a Learning Management System (LMS) where students can ask/chat with admins for each lesson.

As an Admin, I want to get last unseen chats from all lessons sorted by createdAt & seenByAdmin from dashboard.

Here's my Message Model:

{
  studentId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Student"
  },
  lessonId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Lesson"
  },
  from: {
    type: String,
    enum: ["student", "admin"]
  },
  content: {
    type: String
  },
  seenByAdmin: {
    type: Boolean,
    default: false
  },
  createdAt: {
    type: Date,
    default: Date.now()
  }
}

A you can see I don't care which admin is replying to the student.

My desired output:

[
{
  lessonId: ObjectID,
  chats: [
    {
       studentId: ObjectID,
       createdAt: Date, /* of last message */
       seenByAdmin: Boolean, /* of last message */
       content: String /* content of last message (optional) */
    }
  ]
},
{
  lessonId: ObjectID,
  chats: [
    {
       studentId: ObjectID,
       createdAt: Date, /* of last message */
       seenByAdmin: Boolean, /* of last message */
       content: String /* content of last message (optional) */
    },
    {
       studentId: ObjectID,
       createdAt: Date, /* of last message */
       seenByAdmin: Boolean, /* of last message */
       content: String /* content of last message (optional) */
    }
  ]
}
]

OR

[
  {
    lessonId: ObjectID,
    studentId: ObjectID,
    createdAt: Date, /* of last message */
    seenByAdmin: Boolean, /* of last message */
    content: String /* content of last message (optional) */
  },
  {
    lessonId: ObjectID,
    studentId: ObjectID,
    createdAt: Date, /* of last message */
    seenByAdmin: Boolean, /* of last message */
    content: String /* content of last message (optional) */
  }
]

I have been stuck on writing a mongodb aggregation/query and I would appreciate any help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source