【问题标题】:My code is woring in mongodb but not working in pymongo我的代码在 mongodb 中工作,但在 pymongo 中不工作
【发布时间】:2020-09-28 05:11:47
【问题描述】:

我有一个文档在集合中,我想查找文档并更新列表中的元素。

这里是示例数据:

 { 
    {
       "_id" : ObjectId("5edd3faaf6c9d938e0bfd966"),
       "id" : 1,
       "status" : "XXX",
        "number" : [
                        {
                          "code" : "AAA"
                         },
                        {
                          "code" : "CVB"
                        },
                       {
                          "code" : "AAA"
                       },
                       {
                          "code" : "BBB"
                       }
                   ]
    },
    {
       "_id" : ObjectId("asseffsfpo2dedefwef"),
       "id" : 2,
       "status" : "TUY",
        "number" : [
                        {
                          "code" : "PPP"
                         },
                        {
                          "code" : "SSD"
                        },
                       {
                          "code" : "HDD"
                       },
                       {
                          "code" : "IOO"
                       }
                   ]
       }
  }

我打算在["AAA", "BBB"] 中找到"id":1number.code 的值,将number.code 更改为"DDD"。我用以下代码做到了:

db.test.update(
    {
        id: 1,
        "number.code": {$in: ["AAA", "BBB"]}
    },
    {
        $set: {"number.$[elem].code": "VVV"}
    },
        { "arrayFilters": [{ "elem.code": {$in: ["AAA", "BBB"]} }], "multi": true, "upsert": false 
    }
)

它可以在 mongodb shell 中运行,但在 python(带有pymongo)中它不会出现以下错误:

raise TypeError("%s must be True or False" % (option,))
TypeError: upsert must be True or False

请帮助我。我能做什么?

【问题讨论】:

  • 我相信python中的trueTrue&falseFalse!!更改这些布尔拼写错误并对其进行测试。此外,选项multiupsert 都默认为false,只有当您希望它们为true 时才需要指定它们,即; True

标签: python database mongodb nosql pymongo


【解决方案1】:

pymongo 只是语法有点不同。它看起来像这样:

db.test.update_many(
    {
        "id": 1,
        "number.code": {"$in": ["AAA", "BBB"]}
    },
    {
        "$set": {"number.$[elem].code": "VVV"}
    },
    array_filters=[{"elem.code": {"$in": ["AAA", "BBB"]}}],
    upsert=False
)
  • update_many 不需要 multi 标志。
  • upsert 默认为 False,因此也是多余的。

你可以找到 pymongo 的文档here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 2020-10-16
    相关资源
    最近更新 更多