首先,我使用的是 Mongo DB Compass 和 mongo shell。我想更新例如這個欄位:1List.Comment
在這個欄位中,我想用 'ss' 替換 '?'
1List 是一個陣列。在這個陣列中我可以有幾個物件。這些物件包含“評論”欄位。
這是一個示例檔案:
{
"_id":{
"$oid":"12345"
},
"1List":[
{
"Comment": "TE?T Comment",
"TEXT_VALUE":"Another test string",
"REASON":"No Reason"
},
{
"Comment": "TE?T Comment the second",
"TEXT_VALUE":"Another second string",
"REASON":"No Reason again"
}
]
}
這是我在 mongo db shell 中嘗試過的:
db.getCollection('TEST_Collection').aggregate(
[{
$match: {
'1List.Comment': {
$exists: true
}
}
}, {
$unwind: {
path: '$1List',
includeArrayIndex: '1List.CommentArrayIndex',
preserveNullAndEmptyArrays: false
}
}, {
$project: {
'1List.Comment': 1
}
}]
)
.forEach(function(doc,Index) {doc.1List.Comment=doc.1List.Comment.replace(/[?]/g, 'ss');
db.TEST_Collection.updateMany({ "_id": doc._id },{ "$set": { "1List.Comment": doc.1List.Comment } });})
但我收到錯誤訊息: 無法在元素 {1List:.... 中創建欄位“評論”。
有人可以幫助更新這些評論欄位嗎?我在宣告中做錯了什么?
而且,是否有一個簡單的解決方案也可以在更新評論后立即更新“TEXT_VALUE”?
謝謝!
uj5u.com熱心網友回復:
你應該更換這一行
db.TEST_Collection.updateMany({ "_id": doc._id },{ "$set": { "1List.Comment": doc.1List.Comment } });})
和
db.TEST_Collection.updateMany({ "_id": doc._id },{ "$set": { "1List.$[].Comment": doc.1List.Comment } });})
您也可以查看檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362972.html
標籤:数组 json MongoDB mongodb-查询 mongodb-指南针
下一篇:專案欄位默認值不存在
