2

我想更新嵌套文档的记录,我的文档如下所示:

[
  {
    "_id": "60753fd9b249ad0dfa1eeb48",
    "name": "Random Name 1",
    "email": "randomname1@zmel.kom",
    "likings": [
      {
        "breakfast": {
          "eat": "oats",
          "drink": "milk"
        }
      },
      {
        "lunch": {
          "eat": "beef",
          "drink": "pepsi"
        }
      },
      {
        "dinner": {
          "eat": "steak",
          "drink": "champagne"
        }
      }
    ]
  },
  {
    "_id": "60753fd9b249ad0dfa1eeb58",
    "name": "Random Name 2",
    "email": "randomname2@zmel.kom",
    "likings": [
      {
        "breakfast": {
          "eat": "cereals",
          "drink": "coffee"
        }
      },
      {
        "lunch": {
          "eat": "salad",
          "drink": "hot-water"
        }
      },
      {
        "dinner": {
          "eat": "biryani",
          "drink": "apple juice"
        }
      }
    ]
  }
]

现在我想更新drinkfor的值dinnerRandom Name 2但我不知道晚餐的索引,它可能在 之上lunch,也可能在 之下breakfast
这是我在 Python 中尝试过的:

oid = data[0]                # fetched from flask form
to_be_updated = data[1]      # fetched from flask form
update_value = data[2]       # fetched from flask form
condition = {"_id" : oid}
update_value = {
    "$set" : {
        f"likings.{to_be_updated}.drink" : update_value
    }
}
response = mongo.db.food.update(condition, update_value)

但我得到的错误是:
pymongo.errors.WriteError: Cannot create field 'dinner' in element <complete element description>
我计划使用的其他策略是,仅匹配 ID,然后likings通过保持不需要更改的值并更改我想要更改的值来更新。但是这种方法似乎太明显并且在语义上是错误的,因为我正在使用not updating but updating一种策略,即无缘无故地干扰集合模式。有没有办法做到这一点,或者我应该继续我的想法

4

2 回答 2

2

演示MongoDB 游乐场

首先,您的 JSON 中有错误。

JSON

[
  {
    "_id": "60753fd9b249ad0dfa1eeb48",
    "name": "Random Name 1",
    "email": "randomname1@zmel.kom",
    "likings": [
      {
        "breakfast": {
          "eat": "oats",
          "drink": "milk"
        }
      },
      {
        "lunch": {
          "eat": "beef",
          "drink": "pepsi"
        }
      },
      {
        "dinner": {
          "eat": "steak",
          "drink": "champagne"
        }
      }
    ]
  },
  {
    "_id": "60753fd9b249ad0dfa1eeb58",
    "name": "Random Name 2",
    "email": "randomname2@zmel.kom",
    "likings": [
      {
        "breakfast": {
          "eat": "cereals",
          "drink": "coffee"
        }
      },
      {
        "lunch": {
          "eat": "salad",
          "drink": "hot-water"
        }
      },
      {
        "dinner": {
          "eat": "biryani",
          "drink": "apple juice"
        }
      }
    ]
  }
]

尝试这个:

db.collection.update({
  "name": "Random Name 2",
  "likings.dinner": {
    "$exists": true
  }
},
{
  "$set": {
    "likings.$.dinner.drink": "PEPSI"
  }
})

您可以更改dinner为要相应更新的任何字段。

于 2021-04-13T14:52:42.890 回答
-1

如果可能,将列表重构likings为对象。

如果您无法重构,请查看$$[]位置运算符https://docs.mongodb.com/manual/reference/operator/update/positional-all/

于 2021-04-13T09:27:30.830 回答