1、需求
mongodb中存儲(chǔ)了如下結(jié)構(gòu)的數(shù)據(jù)
{
"_id": "A-34yODARDdJSZhQl80eI9",
"sn": "451289155251707905",
"props": {
"name": {
"value": "小王",
"prefix": "",
"suffix": ""
}
},
"propTables": {
"roomInfo": [{
"_id": "P0495-04-021-1-23-2302",
"status": "0",
"props": {
"signPaymentRatio": {
"value": "100.00",
"prefix": "",
"suffix": ""
},
"projectName": {
"value": "項(xiàng)目1",
"prefix": "",
"suffix": ""
}
}
}]
}
}
需要將propTables.roomInfo.signPaymentRatio.value的string類型數(shù)據(jù)改為long類型數(shù)據(jù)
其中propTables.roomInfo是數(shù)組
2、實(shí)現(xiàn)
db.coll.updateMany({"sn":"451289155251707905"},
[{ //使用aggregate更新
$set:{ //set方法進(jìn)行更新,相當(dāng)于addFields
"propTables.roomInfo":{ //新的字段名稱,如果與已有的字段相同,則會(huì)自動(dòng)覆蓋。
$map:{ //使用map方法遍歷
input:"$propTables.roomInfo",//遍歷propTables.roomInfo
as:"r", //alias
in:{
"_id":"$$r._id", //保留_id
"status":"$$r.status", //保留status
"props":{
$mergeObjects: //使用mergeObjects方法實(shí)現(xiàn)long類型替換string類型
[
"$$r.props", //保留舊的props值
{signPaymentRatio:
{
value:{$toLong:{$toDecimal:"$$r.props.signPaymentRatio.value"}}, //轉(zhuǎn)換得到long型的值
prefix:"",
suffix:""
}
}
]
}
}
}
}}
}]
)
參考鏈接
map