【问题标题】:Unable to $unset field in MongoDB nested document无法 $unset MongoDB 嵌套文档中的字段
【发布时间】:2018-07-26 02:27:40
【问题描述】:

我有一个如下所示的文档

{
  "list" :{
    "friends": [
        {
        "Name": "John",
        "Contact": "xyz",
        "Code": "B"
        },
        {
        "Name": "Smith",
        "Contact": "abc",
        "Code": "A"
        }
      ]
   }
}

我正在尝试使用基于过滤器的$unset 运算符删除字段。我的代码如下:

result = db.collection.update_many({"list.friends.code": "A"}, 
         {"$unset": {"list.friends.$.Name": "", "list.frieds.$.Contact": ""}})

但是,我得到pymongo.errors.WriteError: Invalid BSON field name 'list.friends.$.Name'

【问题讨论】:

  • 请注意,您仅在查询中使用小写字符“编码”,这与示例数据中的“编码”不匹配......另外,“炸薯条”可能应该是“朋友” ...
  • 另外,您使用的是哪个 MongoDB 版本?

标签: mongodb pymongo pymongo-3.x


【解决方案1】:

试试这个:

result = db.collection.update_many({"list.friends": { $elemMatch: { "Code":"A"}}}, 
     {"$unset": {"list.friends.$.Name": "", "list.friends.$.Contact": ""}})

【讨论】:

  • 仍然收到“WriteError: Invalid BSON field name 'list.friends.$.Name'”
  • 您使用的是最新版本的驱动吗?
  • 是的。现在是 3.6.0
  • 这是 MongoDB 版本,但是 pymongo 版本呢?
猜你喜欢
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 2017-01-27
  • 1970-01-01
  • 2018-03-09
  • 2020-09-23
  • 2021-12-02
  • 2022-11-04
相关资源
最近更新 更多