![](/img/trans.png)
[英]Update value of key in Object in nested array of objects in MongoDB
[英]Update value in array of string on array of objects mongodb
我正在嘗試更新mongodb中另一個對象數組內部的字符串數組的值
這是模型的一個例子
{
"_id" : ObjectId("5a8cd02f87d4839d279f6559"),
"category" : "0",
"email" : "doctor@doctor.com",
"password" : "doctor",
"name" : "doctor",
"directorys" : [ {
"path" : "doctor@doctor.com/own/",
"files" : [ "" ]
},
{
"path" : "doctor@doctor.com/modified/",
"files" : [ "" ]
},
{
"path" : "doctor@doctor.com/own/pacient1",
"files" : [ "", "README.txt" ]
}
] }
}
所以我試圖將名稱“ README.txt”更新為“ README2.txt”,但我在努力與mongo
我嘗試了這個
db.users.update({"email":"doctor@doctor.com","directorys.files":"README.txt"},{"$set":{"directorys.files.$":"README2.txt"}})
但拋出以下錯誤
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "cannot use the part (directorys of directorys.files.2) to traverse the element ({directorys: [ { path: \"doctor@doctor.com/own/\", files: [ \"\" ] }, { path: \"doctor@doctor.com/modified/\", files: [ \"\" ] }, { path: \"doctor@doctor.com/own/pacient1\", files: [ \"\", \"README.txt\" ] } ]})"
}
})
我想念什么? 我不知道該怎么辦
好吧,我可以執行以下命令來更新數組中的元素
db.users.update({"directorys.files":"README.txt","email":"doctor@doctor.com"},{"$set":{"directorys.$.files.1":"README2.txt"}})
我必須做一些服務器端的工作才能獲得該數字“ 1”,但這可以解決我的問題。
我從這里獲得了靈感https://dba.stackexchange.com/questions/114329/mongodb-update-object-in-array
由於目錄是一個數組,因此我認為您也需要一個數組運算符。 試試這個查詢:
db.users.update(
{"email":"doctor@doctor.com","directorys.files":"README.txt"},
{"$set":{"directorys.$[selectedFiles].files.$":"README2.txt"}},
{arrayFilters: [{"selectedFiles.files": "README.txt"}]}
)
您可以在此處查看有關arrayFilters的更多信息: https ://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#up 。 S []
ArrayFilters允許您獲取一個數組,僅選擇那些符合特定條件的元素,然后將$ set(或任何其他update / upsert運算符)應用於這些元素。
不過,有一點是,這只會更新文件數組中具有README.txt的第一個元素。 如果README.txt存在多次,則不會更新所有這些文件。 如果要更新數組中所有為README.txt的元素,則需要第二個arrayFilter,如下所示:
db.users.update(
{"email":"doctor@doctor.com","directorys.files":"README.txt"},
{"$set":{"directorys.$[selectedDirs].files.$[selectedFiles]":"README2.txt"}},
{arrayFilters: [{"selectedDirs.files": "README.txt"}, {"selectedFiles": "README.txt"}]}
)
那應該選擇具有至少一個README.txt的文件數組的所有目錄元素,然后選擇該文件數組中等於README.txt的所有元素,然后將這些元素設置為README2.txt。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.