Mongo Shell 更新嵌套文档数组
Mongo Shell update nested array of documents
我尝试将数组中文档的属性设置为大写。
这是 link 到 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",
"itemNumber": ""
},
{
"itemName": "BETA305102630",
"itemNumber": "P5000"
},
{
"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
使用游乐场进行演示 link - https://mongoplayground.net/p/5J7Qz97gZoJ
使用游乐场更新演示 link - https://mongoplayground.net/p/8LHEuMakpFF
$map
迭代 value.items
数组 的循环
- 使用
$toUpper
将 itemName
转换为大写
$mergeObjects
将当前对象与更新的 itemName
字段合并
db.collection.update({},
[{
$set: {
"value.items": {
$map: {
input: "$value.items",
in: {
$mergeObjects: [
"$$this",
{ itemName: { $toUpper: "$$this.itemName" } }
]
}
}
}
}
}]
)
我尝试将数组中文档的属性设置为大写。 这是 link 到 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",
"itemNumber": ""
},
{
"itemName": "BETA305102630",
"itemNumber": "P5000"
},
{
"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
使用游乐场进行演示 link - https://mongoplayground.net/p/5J7Qz97gZoJ
使用游乐场更新演示 link - https://mongoplayground.net/p/8LHEuMakpFF
$map
迭代value.items
数组 的循环
- 使用
$toUpper
将 $mergeObjects
将当前对象与更新的itemName
字段合并
itemName
转换为大写
db.collection.update({},
[{
$set: {
"value.items": {
$map: {
input: "$value.items",
in: {
$mergeObjects: [
"$$this",
{ itemName: { $toUpper: "$$this.itemName" } }
]
}
}
}
}
}]
)