MongoDB更新数组元素matching _id和数组中的多个条件

vwhgwdsa  于 2023-04-20  发布在  Go
关注(0)|答案(2)|浏览(205)

我有一个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}
    ]
  }
]

我想更新与_idissues.volissues.num值匹配的issues.freq字段。
具体来说,如果

  1. _id:ObjectId("64390a8796f544082a67146a")
  2. issue.vol:"2"
  3. 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
非常感谢你阅读到这里。如果你对此有一些想法,我也想表达我的感激之情。

3pvhb19x

3pvhb19x1#

使用位置过滤运算符$[<identifier>]更新数组中的特定元素。

db.collection.update({
  "_id": ObjectId("64390a8796f544082a67146a"),
  "issues.vol": "2",
  "issues.num": "1"
},
{
  "$set": {
    "issues.$[i].freq": 45
  }
},
{
  arrayFilters: [
    {
      "i.vol": "2",
      "i.num": "1"
    }
  ]
})

Demo @ Mongo Playground

a9wyjsp7

a9wyjsp72#

对应PyMongo查询:

如果它对任何使用PyMongo的人都有帮助(注意:MongoDB的arrayFilters在PyMongo中变成了array_filters):

import bson

edvol= "2"
ednum= "1"
per_col.update_one(
    {
        '_id': bson.ObjectId("64390a8796f544082a67146a"),
        "issues.vol": edvol,
        "issues.num": ednum
    }, 
    {'$set': {"issues.$[i].freq": 45}}, 
    upsert=False,
    array_filters=[{'i.vol': edvol, 'i.num': ednum}]
)

相关问题