我正在尝试更新 mongodb 中字符串数组的值,该数组位于另一个对象数组内
这是模型的示例
{
"_id" : ObjectId("5a8cd02f87d4839d279f6559"),
"category" : "0",
"email" : "[email protected]",
"password" : "doctor",
"name" : "doctor",
"directorys" : [ {
"path" : "[email protected]/own/",
"files" : [ "" ]
},
{
"path" : "[email protected]/modified/",
"files" : [ "" ]
},
{
"path" : "[email protected]/own/pacient1",
"files" : [ "", "README.txt" ]
}
] }
}
所以我试图将名称“README.txt”更新为“README2.txt”,但我正在与 mongo 作斗争
我试过这个
db.users.update({"email":"[email protected]","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: \"[email protected]/own/\", files: [ \"\" ] }, { path: \"[email protected]/modified/\", files: [ \"\" ] }, { path: \"[email protected]/own/pacient1\", files: [ \"\", \"README.txt\" ] } ]})"
}
})
我缺少什么?我不知道该怎么办
由于目录是一个数组,我认为你也需要一个数组运算符。尝试这个查询:
db.users.update(
{"email":"[email protected]","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 (或任何其他更新/更新插入运算符)应用于这些元素。
有一件事是,这只会更新文件数组中包含 README.txt 的第一个元素。如果 README.txt 出现多次,您将不会更新所有内容。如果要更新数组中 README.txt 中的所有元素,则需要第二个 arrayFilter,如下所示:
db.users.update(
{"email":"[email protected]","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。
我可以执行以下命令来更新数组中的元素
db.users.update({"directorys.files":"README.txt","email":"[email protected]"},{"$set":{"directorys.$.files.1":"README2.txt"}})`
我必须做一些服务器端工作才能动态获取数字“1”,但这解决了我的问题。
我从这里得到了灵感https://dba.stackexchange.com/questions/114329/mongodb-update-object-in-array