I have a database of documents called ChatRooms
stored in MongoDB with the following structure:
{
_id: ObjectId('4654'),
messages: [
{
user: ObjectId('1234'),
sentAt: ISODate('2022-03-01T00:00:00.000Z')
},
{
user: ObjectId('1234'),
sentAt: ISODate('2022-03-02T00:00:00.000Z')
},
{
user: ObjectId('8888'),
sentAt: ISODate('2022-03-03T00:00:00.000Z')
},
]
}
My goal is to filter the messages
array within an aggregate
pipeline so that I only get one entry for each unique userId
. The desired result should look like this (or something similar where the array does not contain duplicate entries for the same user
id):
{
_id: ObjectId('4654'),
messages: [
{
user: ObjectId('1234'),
sentAt: ISODate('2022-03-01T00:00:00.000Z')
},
{
user: ObjectId('8888'),
sentAt: ISODate('2022-03-03T00:00:00.000Z')
},
]
}
Is there a way to achieve this? Any assistance would be greatly appreciated.