如何将值更新为MongoDB文档中的嵌套对象数组?
我有以下文档需要进行更新。
{
"_id": "Colorcode_1",
"Combination": [
{
"color": [
{
"mixture": [
"Red",
"Green"
]
}
],
"code": "Maroon"
},
{
"color": [
{
"mixture": [
"Yellow",
"Green"
]
}
],
"code": "Light Green"
}
]
}
现在我需要做的是更新通过在“混合”中添加值“蓝色”的值来“代码”是“栗色”的字段。这样的东西。需要使用 $ addtoset
{
"_id": "Colorcode_1",
"Combination": [
{
"color": [
{
"mixture": [
"Red",
"Green",
"Blue"
]
}
],
"code": "Maroon"
},
{
"color": [
{
"mixture": [
"Yellow",
"Green"
]
}
],
"code": "Light Green"
}
]
}
对此进行任何帮助将非常有帮助。
I have following document on which the update needs to be done.
{
"_id": "Colorcode_1",
"Combination": [
{
"color": [
{
"mixture": [
"Red",
"Green"
]
}
],
"code": "Maroon"
},
{
"color": [
{
"mixture": [
"Yellow",
"Green"
]
}
],
"code": "Light Green"
}
]
}
Now what I need to do is to update the document by adding the value "Blue" in the "mixture" field where "code" is "Maroon". Something like this. This needs to be done using $addToSet
{
"_id": "Colorcode_1",
"Combination": [
{
"color": [
{
"mixture": [
"Red",
"Green",
"Blue"
]
}
],
"code": "Maroon"
},
{
"color": [
{
"mixture": [
"Yellow",
"Green"
]
}
],
"code": "Light Green"
}
]
}
Any help regarding this would be highly helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是带有ArrayFilters的选项:
解释:
playground
Here is option with arrayFilters:
Explained:
playground
由于数据模型,我发现此更新很困难,我希望您会得到更好/更简单的答案。
无论如何,这是您可以做到的一种方法。我会在更多/不同的数据上对其进行测试,以确保其正确。
尝试一下 mongoplayground.net.net 。
I found this update difficult because of the data model, and I'm hoping you'll get a better/simpler answer.
Anyway, here's one way you could do it. I would test this on more/different data to insure it's correct.
Try it on mongoplayground.net.