i want to get createdAt field of last message of a specific user in agroup
suppose here userId is any user . i want to fetch his last message in a group which he sent and want to get createdAt field of that message. then i want to compare all documents whose createdAt time is less then this document and want to fetch 1st document in that List.
in below code 1st i sorted documents reversely now i want to get createdAt field of last message of user i put if condition but remain unsuccesfull .try with arrays but still no success.
it returns createdAt field of last document processed. i want createdAt field of that document where senderId field value is equal to userId
I dont want another query .Can anyone help me to get createdAt field of that document?
please dont put simple match condition because match will give one document and all other document doesnt go to next stage . after that i also want compare that createdAt field with other documents createdAt field.
let userId = any userId in this group
let groupId = any groupId
let result = await groupChatModel.aggregate([
{
$match: {
groupId: groupId
}
},
{
"$sort": {
"createdAt": -1
}
},
{
$project: {
LastmessageCreatedAt: {
$cond: {
if: {
$eq: [userId, "$senderId"]
},
then: $createdAt",
else: "$$REMOVE" // i want nothing here but cant get rid of this else condition
}
}
}
}
]),