![](/img/trans.png)
[英]How to group documents of a collection to a map with unique field values as key and count of documents as mapped value in mongodb?
[英]How to get Unique Data and Mapped with Field in MongoDB
我是 Mongo 的新手,并试图将 model 数据和 map model 代码分组到 Z20F35E630DAF44DB84C39 年。
Sample Data:
[
{
"model":[
{
"modelCode":"Z34L",
"modelName":"370Z",
"modelYear":"2009 - Present"
}
]
},
{
"model":[
{
"modelCode":"Z35L",
"modelName":"370Z",
"modelYear":"2010 - Present"
}
]
}
]
预期 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. 当我使用这种方法但得到重复数据时。 https://mongoplayground.net/p/Je0bR6ki7kP
你实际上很接近。 唯一不正确的是您正在使用整个model
object 执行$addToSet
,这会导致重复数据删除失败。 你可以试试下面的代码:
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"
}
}
}
])
这是Mongo游乐场供您参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.