【发布时间】:2020-05-22 18:42:55
【问题描述】:
我想更新 mongo 文档中的单个值,该值是数组数组的数组,
这是我到目前为止的代码......但它不起作用。我想我需要使用图表上的 $ 运算符来访问当前选择的 chorePerson...但不确定它是如何工作的。
我真的在 mongoDB 语法和更新数组方面苦苦挣扎
这是我的数据集,我在各自的数组中分别放入了 t1、t2 和 t3...
[
{
"_id": "5e3d891d956bb31c307d8146",
"t1": 0,
"affiliation": "800_800",
"year": 2020,
"month": "February",
"weekNumber": 6,
"weekStart": "02/02/2020",
"weekEnd": "02/08/2020",
"chart": [
{
"t2": 0,
"_id": "5e3d8a6358a3d92448e85aa5",
"ordinal": 5,
"ordinalString": "Friday",
"chorePerson": [
{
"completed": false,
"t3": 0,
"_id": "5e3d8a6358a3d92448e85aa7",
"person": "Frank",
"personID": "5e2891587678601434f6929c",
"phone": "8008008002",
"chore": "Another one",
"choreID": "5e39ca3949acee16fc280c98"
}
]
}
],
"date": "2020-02-07T16:03:47.770Z",
"__v": 0
}
]
我已经能够使用这个查询更新 t1 和 t2:
{"_id":"5e3d891d956bb31c307d8146","chart._id":"5e3d9260fc365c2d080a32ce"}
和一组调用
{"$set":{"t1":1,"chart.$.t2":2}}
但我不知道如何在数组中再下降一层
这是我的查询:我对“图表 [1]”进行了硬编码,以尝试强制它仅获取该记录
{"_id":"5e3d891d956bb31c307d8146","chart._id":"5e3d8a6358a3d92448e85aa5","chart[1].chorePerson._id":"5e3d8a6358a3d92448e85aa7"}
这是我的“设置”电话
{"$set":{"t1":1,"chart.$.t2":2,"chart.$[].chorePerson.$.t3":3}}
当我在我的程序中运行它时,我得到:
error Updating the path 'chart.$[].chorePerson.$.t3' would create a conflict at 'chart'
更新 1
所以我尝试了这个:
{"_id":"5e3d93777f099b28b0fff2ae","chart._id":"5e3d953ed92a082738e8e2b9","chart.chorePerson._id":"5e3d953ed92a082738e8e2bb"}
{"$set":{"t1":1,"chart.$.t2":2,"chart.$.chorePerson.$.t3":3}}
这给了我:
error Too many positional (i.e. '$') elements found in path 'chart.$.chorePerson.$.t3
所以我想我会回到 whoami 发布的答案:
{"$set":{"t1":1,"chart.$.t2":2,"chart.$[].chorePerson.$.t3":3}}
这给了我:
error Updating the path 'chart.$[].chorePerson.$.t3' would create a conflict at 'chart'
更新 2
所以我尝试将 set 语句中的 [] 移动到图表中。$.chorePerson
{"$set":{"t1":1,"chart.$.t2":2,"chart.$.chorePerson.$[].t3":3}}
并仅选择相关的 chorePerson (5e3da771e08e3e31ac420004)
{"_id":"5e3da771e08e3e31ac41fffd","chart._id":"5e3da771e08e3e31ac420002","chart.chorePerson._id":"5e3da771e08e3e31ac420004"}
这让我更接近...现在数据正在正确的家务图表和图表中设置,但是所有 chorePerson 字段都正在更新,即使我的选择应该只返回家务人员'5e3da771e08e3e31ac420004'
【问题讨论】:
-
stackoverflow.com/users/7237613/whoami - 感谢您在这方面的帮助...我已用 ID 信息更新了问题
标签: javascript mongodb