I wrote a simple query in MongoDB to get all data related to the product ID. Now I want to convert my response into an array of objects. Please see below.
Query:
db.collection.find({ "product_id": 1212 })
Getting response:
[
{
"product_id": 1212,
"name": "sprit",
"category_id": 1234,
"category": "drink"
},
{
"product_id": 1212,
"name": "sprit",
"category_id": 2122,
"category": "soda"
},
{
"product_id": 1212,
"name": "sprit",
"category_id": 2121,
"category": "mocktail"
},
{
"product_id": 1212,
"name": "sprit",
"category_id": 2121,
"category": "mocktail"
}
]
I want to convert the data in a different format by MongoDB query and remove duplicate category_id
.
Required response:
[
{
"product_id": 1212,
"name": "sprit",
"categogies": [
{
"category_id": 1234,
"category": "drink"
},
{
"category_id": 2122,
"category": "soda"
},
{
"category_id": 2121,
"category": "mocktail"
}
]
}
]
Group by product_id
via $group
and add distinct document into the categogies
array via $addToSet
.
db.collection.aggregate([
{
$match: {
"product_id": 1212
}
},
{
$group: {
_id: "$product_id",
name: {
$first: "$name"
},
categogies: {
$addToSet: {
"category_id": "$category_id",
"category": "$category"
}
}
}
},
{
$project: {
_id: 0,
product_id: "$_id",
name: "$name",
categogies: "$categogies"
}
}
])