I am new to MongoDB, I want to get data in sections from the array.
{
"name":"User name",
"messages":[
{
"message":"Message 1",
"date":"2022-05-12T00:00:00.000Z"
},
{
"message":"Message 2",
"date":"2022-05-12T00:00:00.000Z"
},
{
"message":"Message 3",
"date":"2022-05-13T00:00:00.000Z"
},
{
"message":"Message 4",
"date":"2022-05-13T00:00:00.000Z"
},
{
"message":"Message 5",
"date":"2022-05-13T00:00:00.000Z"
}
]
}
The results I want are
[
{
"date":"2022-05-12T00:00:00.000Z",
"messages":[
{
"message":"Message 1",
"date":"2022-05-12T00:00:00.000Z"
},
{
"message":"Message 2",
"date":"2022-05-12T00:00:00.000Z"
}
]
},
{
"date":"2022-05-13T00:00:00.000Z",
"messages":[
{
"message":"Message 3",
"date":"2022-05-13T00:00:00.000Z"
},
{
"message":"Message 4",
"date":"2022-05-13T00:00:00.000Z"
},
{
"message":"Message 5",
"date":"2022-05-13T00:00:00.000Z"
}
]
}
]
I'm not familiar with MongoDB aggregation, I have looked at many questions on stack overflow but didn't find any that helped me.
Is this possible to do? If yes any help would be greatly appreciated. :)
CodePudding user response:
$unwind
- Deconstructmessages
array to multiple documents.$group
- Group bymessages.date
and addmessages
document intomessages
array.$project
- Decorate output documents.
db.collection.aggregate([
{
$unwind: "$messages"
},
{
$group: {
_id: "$messages.date",
messages: {
$push: "$messages"
}
}
},
{
$project: {
_id: 0,
date: "$_id.date",
messages: 1
}
}
])