在 MongoDB 的数组中更新 Object-Element
Update Object-Element in Array in MongoDB
我在 Whosebug 上阅读了其他几篇文章,但没有找到任何 'general' 答案。
假设我有一个这样的结构:
{
personsName: "Bob",
children: [
{childsName: "Alice", age: "9", weight: "40"}
{childsName: "Peter", age: "12", weight: "80"}
]
}
现在我想编辑彼得斯的体重,因为它实际上是“45”
我试过了:
.update(
{ personsName: "Bob", children.childsName: "Peter"},
{
$set: {children: {weight :"45" } }
}
)
对我来说这应该有效...将所有名为 "Peter" 且属于 "Bob" 的 children 的 children 权重更新为“45” ...
我看到了一些解决方案,它们按索引更新数组,但假设我们不知道索引,我们想按子 属性 "childsName".
更新
这样做的一般方法是什么?
如果你确定Bob有不超过1个Peter,你可以使用positional operator如下:
.update(
{ personsName: "Bob", "children.childsName": "Peter"},
{
$set: {"children.$.weight" :"45" }
}
)
请注意,操作员只更新第一个匹配的子文档,并且只更新到 1 级。
我在 Whosebug 上阅读了其他几篇文章,但没有找到任何 'general' 答案。
假设我有一个这样的结构:
{
personsName: "Bob",
children: [
{childsName: "Alice", age: "9", weight: "40"}
{childsName: "Peter", age: "12", weight: "80"}
]
}
现在我想编辑彼得斯的体重,因为它实际上是“45”
我试过了:
.update(
{ personsName: "Bob", children.childsName: "Peter"},
{
$set: {children: {weight :"45" } }
}
)
对我来说这应该有效...将所有名为 "Peter" 且属于 "Bob" 的 children 的 children 权重更新为“45” ... 我看到了一些解决方案,它们按索引更新数组,但假设我们不知道索引,我们想按子 属性 "childsName".
更新这样做的一般方法是什么?
如果你确定Bob有不超过1个Peter,你可以使用positional operator如下:
.update(
{ personsName: "Bob", "children.childsName": "Peter"},
{
$set: {"children.$.weight" :"45" }
}
)
请注意,操作员只更新第一个匹配的子文档,并且只更新到 1 级。