You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python操作MongoDB实现Discord机器人金币数据查询修改更新方法咨询

实现方案

你可以直接用MongoDB的$inc原子更新操作符完成需求,不需要先查询再修改,既简化代码也能避免并发修改导致的数据不一致问题,完整的roll指令代码如下:

@bot.command()
async def roll(ctx):
    # 生成四类金币的随机收益
    coinAearn = random.randint(1, 100)
    coinBearn = random.randint(1, 100)
    coinCearn = random.randint(1, 100)
    coinDearn = random.randint(1, 100)
    
    # 以触发指令的用户ID作为查询条件
    user_id = str(ctx.author)
    # 执行更新操作,$inc对应字段自增对应收益值
    update_result = mycol.update_one(
        {"_id": user_id},
        {
            "$inc": {
                "coinA": coinAearn,
                "coinB": coinBearn,
                "coinC": coinCearn,
                "coinD": coinDearn
            }
        },
        # 可选:如果用户没有账户数据则自动初始化,适配指令上线前就加入的老用户
        upsert=True
    )
    
    # 可选:给用户发送收益提示
    await ctx.send(f"本次roll点收益:\ncoinA +{coinAearn}\ncoinB +{coinBearn}\ncoinC +{coinCearn}\ncoinD +{coinDearn}")

补充说明

  • 如果不需要自动初始化老用户账户,去掉upsert=True参数即可,此时如果用户不存在update_result.matched_count会返回0,你可以自行补充提示用户账户不存在的逻辑。
  • 如果你需要先查询用户当前的金币余额再返回给用户,可以在更新完成后调用mycol.find_one({"_id": user_id})获取最新数据即可。

内容的提问来源于stack exchange,提问作者Neimos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 20:21:03