问题描述
我尝试将数组内文档的属性设置为大写。 这是 mongodb 游乐场的链接 https://mongoplayground.net/p/BTP_h3kqK_S
这是一个文档示例
{
"_id": ObjectId("5e786a078bc3b3333627341e"),"value": {
"items": [
{
"itemName": "alpha305102992","itemNumber": ""
},{
"itemName": "beta305102630","itemNumber": "P5000"
},{
"itemName": "gamma305102633 ","itemNumber": ""
}
]
}
}
我尝试将“itemName”设置为大写。
我想要的结果是:
{
"_id": ObjectId("5e786a078bc3b3333627341e"),"value": {
"items": [
{
"itemName": "ALPHA305102992",{
"itemName": "BETA305102630",{
"itemName": "GAMMA305102633 ","itemNumber": ""
}
]
}
}
解决方法
演示 - https://mongoplayground.net/p/geb1MRHXNyk
使用update-documents-with-aggregation-pipeline
db.collection.update({},[
{
$set: {
value: {
items: { // set item to loop only once
$map: {
input: "$value.items",// loop over items
in: {
$mergeObjects: [ // merge document
"$$this",{ itemName: { $toUpper: "$$this.itemName" } } // change individual itemName to upper
]
}
}
}
}
}
}
])
聚合演示 - https://mongoplayground.net/p/9wtSkyjC88c
带有游乐场链接的演示 - https://mongoplayground.net/p/5J7Qz97gZoJ
使用 Playground 链接更新演示 - https://mongoplayground.net/p/8LHEuMakpFF
,-
$map
迭代value.items
数组的循环 - 使用
itemName
将$toUpper
转换为大写 -
$mergeObjects
将当前对象与更新后的itemName
字段合并
db.collection.update({},[{
$set: {
"value.items": {
$map: {
input: "$value.items",in: {
$mergeObjects: [
"$$this",{ itemName: { $toUpper: "$$this.itemName" } }
]
}
}
}
}
}]
)