【问题标题】:How can I update a MongoDB document with python?如何使用 python 更新 MongoDB 文档?
【发布时间】:2018-07-21 05:39:10
【问题描述】:

我想做的是用 python 和 discord.py 更新一个 MongoDB 文档,但是我放的代码不起作用。

elif string2 == "add":
    if string3 == "administrator":
        cur = coll.find({"_id" : string1.id})
        for doc in cur:
            if doc["perm"] == "administrator":
                await self.bot.say("Permission {} already found on db for user {}".format(string3, string1.name))
            else:
                db.users.update_one({"_id" : string1.id, "name" : string1.name, "perm" : "administrator"}, upsert=False)
                await self.bot.say("Permissions updated on db for user {}".format(string1.name))

以下是错误。

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: update_one() missing 1 required positional argument: 'update'

来自用户集合的文档:

_id: "191598787410526208"
name: "Stevyb0t"
perm: "administrator"

【问题讨论】:

  • 您需要将第二个参数传递给update_one,以便更新文档并避免此类错误。它看起来像这样,db.users.update_one({}, {}, upsert=False)
  • @NileshSingh ,它说“更新只适用于 $ 运营商”。
  • 如果您可以使用edit 链接更新您的问题并向我们展示来自users 集合的示例文档,将会有很大帮助
  • @chridam ,完成。
  • 就像@NileshSingh 所说的,试试db.users.update_one({"_id" : string1.id}, {"$set": {"name" : string1.name, "perm" : "administrator"}}, upsert=False)

标签: python mongodb pymongo discord.py


【解决方案1】:

基本上是其他人评论的内容,但有一些格式使其更清晰:

db.users.update_one(
    {"_id": string1.id},
    {"$set":
        {"name": string1.name,
        "perm": "administrator"
    }})

我还删除了upsert=False,因为这是默认值,所以你不需要指定它 - 当然,明确会有所帮助

编辑:阅读所有的 cmets,已经提出了将接受的评论作为答案的建议,所以就在这里。我的回答和那条评论没有什么不同

【讨论】:

    【解决方案2】:

    如果您的 id 是字符串,您可能需要将其转换为 ObjectId。此外,您可以打印更新结果,并检查是否成功:

    from bson import ObjectId
    
    result = db.users.update_one(
                 {"_id": ObjectId(string1.id)},
                 {"$set":
                     {"name": string1.name,
                      "perm": "administrator"}
                 })
    
    logger.debug('update result: {}'.format(result.raw_result))
    if result.matched_count > 0:
        # Success code goes here
        pass
    else:
        # Failure code goes here
        pass
    

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 2017-01-06
      • 2016-11-04
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 2019-03-04
      相关资源
      最近更新 更多