Reputation: 155
I am new on Mongo and trying to group the model data and map model code to model year.
Sample Data:
[
{
"model":[
{
"modelCode":"Z34L",
"modelName":"370Z",
"modelYear":"2009 - Present"
}
]
},
{
"model":[
{
"modelCode":"Z35L",
"modelName":"370Z",
"modelYear":"2010 - Present"
}
]
}
]
Expected Output:
[
{
"modelName":"370Z",
"modelYear":{
"Z34L":"2009 - Present",
"Z35L":"2010 - Present"
}
}
]
in the above example, we group by model name and found 2 model years and put the model year key with key as model code and value as model year. while I am using this approach but getting duplicate data. https://mongoplayground.net/p/Je0bR6ki7kP
Upvotes: 0
Views: 40
Reputation: 15227
You are actually pretty close. The only thing that is incorrect is that you are doing $addToSet
using the whole model
object, which makes the de-duplication failed. You can try below code:
db.collection.aggregate([
{
"$unwind": "$model"
},
{
"$group": {
"_id": {
"modelName": "$model.modelName"
},
"modelYearListing": {
"$addToSet": {
k: "$model.modelCode",
v: "$model.modelYearListing"
}
}
}
},
{
"$project": {
_id: 0,
"modelName": "$_id.modelName",
modelYear: {
"$arrayToObject": "$modelYearListing"
}
}
}
])
Here is the Mongo playground for your reference.
Upvotes: 1