我有一个MongoDB集合:
收藏:
[
{
"_id": ObjectId("64390a7196f544082a671469"),
"name": "Sydney",
"issues": [
{"vol": "2", "num": "1", "freq": 5},
{"vol": "1", "num": "2", "freq": 7}
]
},
{
"_id": ObjectId("64390a8796f544082a67146a"),
"name": "Canton",
"issues": [
{"vol": "2", "num": "2", "freq": 9},
{"vol": "1", "num": "3", "freq": 9},
{"vol": "2", "num": "1", "freq": 11}
]
}
]
我想更新与_id
、issues.vol
和issues.num
值匹配的issues.freq
字段。
具体来说,如果
_id:ObjectId("64390a8796f544082a67146a")
,issue.vol:"2"
和issue.num:"1"
issue.freq
将更新为45
(从11
的现有值)。
以下是我到目前为止的查询:
查询:
db.collection.update({
"_id": ObjectId("64390a8796f544082a67146a"),
"issues.vol": "2",
"issues.num": "1"
},
{
"$set": {
"issues.$.freq": 45
}
})
问题是,它更新了("_id": ObjectId("64390a8796f544082a67146a")
,"issues.vol": "2"
and "issues.num": "2"
)的值,而不是("_id": ObjectId("64390a8796f544082a67146a")
,"issues.vol": "2"
and "issues.num": "1"
)。我做错了什么?
结果集(我上面查询后):
[
{
"_id": ObjectId("64390a7196f544082a671469"),
"issues": [
{"freq": 5, "num": "1", "vol": "2"},
{"freq": 7, "num": "2","vol": "1"}
],
"name": "Sydney"
},
{
"_id": ObjectId("64390a8796f544082a67146a"),
"issues": [
{"freq": 45, "num": "2", "vol": "2"},
{"freq": 9, "num": "3", "vol": "1"},
{"freq": 11, "num": "1", "vol": "2"}
],
"name": "Canton"
}
]
Mongo playground link
非常感谢你阅读到这里。如果你对此有一些想法,我也想表达我的感激之情。
2条答案
按热度按时间3pvhb19x1#
使用位置过滤运算符
$[<identifier>]
更新数组中的特定元素。Demo @ Mongo Playground
a9wyjsp72#
对应PyMongo查询:
如果它对任何使用PyMongo的人都有帮助(注意:MongoDB的
arrayFilters
在PyMongo中变成了array_filters
):