我需要从数组中重命名一个文档字段。这是我的文件:
"_id" : ObjectId("5bda09a090ecff10f7275781"),
"color" : "blue",
"levels" : [
{
"level" : 1,
"tag" : "AB"
},
{
"level" : 2,
"tag" : "AA"
},
{
"level" : 3,
"tag" : "BB"
}
]我需要在我的平台上将子文档字段重命名为indice,但是我没有成功。
这是我的聚合函数和不想要的结果:
db.test.aggregate({$project: {color:1, 'levels.tag':1, 'levels.indice': '$levels.level'}}).pretty()不必要的结果:
"_id" : ObjectId("5bda09a090ecff10f7275781"),
"color" : "blue",
"levels" : [
{
"tag" : "AB",
"indice" : [
1,
2,
3
]
},
{
"tag" : "AA",
"indice" : [
1,
2,
3
]
},
{
"tag" : "BB",
"indice" : [
1,
2,
3
]
}
]我只希望有以下结果:
"_id" : ObjectId("5bda09a090ecff10f7275781"),
"color" : "blue",
"levels" : [
{
"indice" : 1,
"tag" : "AB"
},
{
"indice" : 2,
"tag" : "AA"
},
{
"indice" : 3,
"tag" : "BB"
}
]有谁可以帮我?非常感谢!
发布于 2018-10-31 20:26:34
使用$map迭代级别并重命名字段。保留所有现有字段的$addFields。
db.test.aggregate({
"$addFields":{
"levels":{
"$map":{
"input":"$levels",
"in":{
"indice":"$$this.level",
"tag":"$$this.tag"
}
}
}
}
})https://stackoverflow.com/questions/53091363
复制相似问题