How to query the most recent records each having a different unique field in mongodb?

Viewed 12

I am working on creating a chat that displays an x amount of last messages sent and I am using a mongodb database. I am currently using the aggregate framework for more complex queries and have gotten as far as getting unique entries but they are not the most recently sent entries.

I am attempting to get the most recent message records that matches the senderId with different conversationId's to show the last messaged people.

Schema

const MessageSchema = new mongoose.Schema({
    conversationId: {
        type:mongoose.Schema.Types.ObjectId,
        ref:"Conversation"
    },
    senderId:{
        type:mongoose.Schema.Types.ObjectId,
        required:true,
        ref:"Users"
    },
    recipientId:{
        type:mongoose.Schema.Types.ObjectId,
        required:true,
        ref:"Users"
    },
    message:{
        type:String
    }
}, {timestamps:true})

Aggerate query

    const recentlyMessaged = await MessageModel.aggregate([
        {
            $match:{ senderId:mongoose.Types.ObjectId(currentUserId) }
        },
        {
            $sort: {
                createdAt: -1
            }
        },
        {
            $group: {_id: "$conversationId",
            doc: {$first: "$$ROOT"}}
        },
        {
            $limit:3
        },
    ])
0 Answers
Related