我有一個帶有 Mongo 資料庫的應用程式,該資料庫的檔案存盤結構如下:
{
"_id" : ...,
"order_no": 12345,
"results": [
{
"a": "customer",
"b": "name",
"result": "John Doe"
},
{
"a": "order_info",
"b": "date",
"result": "2022-04-19T00:00:00.000Z"
},
{
"a": "order_type",
"b": "type",
"result": "Standard"
}
]
}
因此,假設我需要將公司名稱更改為“John Doe Ltd”,我正在努力更新屬于客戶 John Doe 的所有檔案,以便客戶名稱反映此更改。
我試過了
collection.updateMany( { "results.a": "customer", "results.b": "name", "results.result": "John Doe" }, [{ $set: { "results.a": "customer", "results.b": "name", "results.result": "John Doe Ltd" } }] )
但我得到一個錯誤......"Cannot create field 'a' in element..."
我希望有人能指出我正確的方向。提前致謝。
uj5u.com熱心網友回復:
db.collection.update({
"results.a": "customer",
"results.b": "name",
"results.result": "John Doe"
},
{
"$set": {
"results.$.a": "customer",
"results.$.b": "name",
"results.$.result": "John Doe Ltd"
}
})
要更新陣列中的特定物件,您必須使用位置$運算子來增加匹配的檔案。
但請注意,它只更新陣列中第一個匹配的物件。如果一個特定查詢有多個物件匹配,則僅更新第一個。
以下是參考代碼: https ://mongoplayground.net/p/o4gFzyQ8HTn
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459361.html
標籤:mongodb
上一篇:當if陳述句正確時,將if陳述句轉到else陳述句的把手
下一篇:無法理解前端和后端之間的連接
