I have 2 collections, messages and chats. How can I use aggregation to group and messages of the same conversation id into an array and put it in the field of array of conversations? In addition, I want to sort the messeages by its timestamp and remove the conversationId.
messages schema:
conversationId: String,
content: String,
timestamp: Date
chats schema:
userId: ObjectId,
conversations: [{
id: String
name: String
}]
Example output:
{
userId: ObjectId,
conversations: [
{
id: "conv1",
name: "a",
messages: [{content: "bruh", timestamp: Date}, ...]
},
{
id: "conv2",
name: "b",
messages: [{content: "happy happy happy", timestamp: Date}, ...]
}
]
}
I tried this but I do not know what to do next. Perhaps $bucket?
db.chats.aggregate([
{
$lookup: {
"from": "messages",
"localField": "conversations.id",
"foreignField": "conversationId",
"pipeline": [
{
$project: {
"conversationId": 0
}
},
{
$sort: {
"timestamp": 1,
"_id": 1
}
}
],
"as": "messages"
}
}
])