MongoDB 更新数组中的错误子文档
MongoDB updating wrong subdocument in an array
我的 gamefamilies 合集看起来像这样
{
"_id": ObjectId('54cc3ee7894ae60c1c9d6c74'),
"game_ref_id": "REF123",
..
"yearwise_details": [
{
"year": 1,
...
"other_details": [
{
"type": "cash",
"openingstock": 988
..
},
{
"type": "FLU",
"openingstock": 555
..
},
..other items
]
},
{
"year": 2,
...
"other_details": [
{
"type": "cash",
"openingstock": 3000,
....
},
...
{
"type": "ghee",
"openingstock": 3000,
...
},
..
]
}
]
}
我的更新查询
db.gamefamilies.update({"game_ref_id": "REF123", "teamname": "manisha","yearwise_details.year": 2, "yearwise_details.other_details.type": "ghee"}, {"$set": {"yearwise_details.0.other_details.$.openingstock": 555} });
文档正在正确拾取。我希望更新第 2 年的项目 type="ghee" 但第 1 年的第 2 个项目(类型 FLU)得到更新。我做错了什么?
如有任何帮助,我们将不胜感激。
问候
马尼沙
遗憾的是,尚不支持嵌套 $ positional operator 更新。
因此您可以使用
对更新进行硬编码
db.gamefamilies.update({"game_ref_id": "REF123",
"teamname": "manisha",
"yearwise_details.year": 2,
"yearwise_details.other_details.type": "ghee"},
{"$set":
{"yearwise_details.1.other_details.$.openingstock": 555}});
但是请注意 yearwise_details.1.other_details
是硬编码的,您需要数组的第二个值(它是 0 索引的,所以 1
是引用第二个元素)。我假设您找到了问题中的命令,因为它适用于数组的第一个元素。但它只会对第一个元素起作用,上面的命令只会对第二个元素起作用。
我的 gamefamilies 合集看起来像这样
{
"_id": ObjectId('54cc3ee7894ae60c1c9d6c74'),
"game_ref_id": "REF123",
..
"yearwise_details": [
{
"year": 1,
...
"other_details": [
{
"type": "cash",
"openingstock": 988
..
},
{
"type": "FLU",
"openingstock": 555
..
},
..other items
]
},
{
"year": 2,
...
"other_details": [
{
"type": "cash",
"openingstock": 3000,
....
},
...
{
"type": "ghee",
"openingstock": 3000,
...
},
..
]
}
]
}
我的更新查询
db.gamefamilies.update({"game_ref_id": "REF123", "teamname": "manisha","yearwise_details.year": 2, "yearwise_details.other_details.type": "ghee"}, {"$set": {"yearwise_details.0.other_details.$.openingstock": 555} });
文档正在正确拾取。我希望更新第 2 年的项目 type="ghee" 但第 1 年的第 2 个项目(类型 FLU)得到更新。我做错了什么?
如有任何帮助,我们将不胜感激。
问候 马尼沙
遗憾的是,尚不支持嵌套 $ positional operator 更新。
因此您可以使用
对更新进行硬编码db.gamefamilies.update({"game_ref_id": "REF123",
"teamname": "manisha",
"yearwise_details.year": 2,
"yearwise_details.other_details.type": "ghee"},
{"$set":
{"yearwise_details.1.other_details.$.openingstock": 555}});
但是请注意 yearwise_details.1.other_details
是硬编码的,您需要数组的第二个值(它是 0 索引的,所以 1
是引用第二个元素)。我假设您找到了问题中的命令,因为它适用于数组的第一个元素。但它只会对第一个元素起作用,上面的命令只会对第二个元素起作用。