[英]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.