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. 🙂
2
Answers
$unwind
– Deconstructmessages
array to multiple documents.$group
– Group bymessages.date
and addmessages
document intomessages
array.$project
– Decorate output documents.Sample Mongo Playground
You can use aggregation to get your desired output.