【问题标题】:MongoDB(py) - How to retreive data, modify it, update it?MongoDB(py) - 如何检索、修改、更新数据?
【发布时间】:2021-09-13 13:11:07
【问题描述】:

这是为 MongoDB 使用 python 的不和谐机器人。 我想知道如何从 ID 中获取某个值,然后我想修改该值并更新它。

//这里我设置了Database和Collection

db = client.mymongodatabase #Database
mycol= db.mymongocollection #Collection in Database

//这里我将条目加入到Mongo数据库集合中

@bot.event
async def on_member_join(member):
  setupbank = ({"_id":(str(member)), "coinA":100, "coinB":50,"coinC":50,"coinD":50})
  mycol.insert_one(setupbank)

//问题。我有一个函数可以生成 4 个随机整数,每种硬币类型一个。但是如何检索硬币数据并将随机收益添加到现有值中,最后更新 mongodb 集合中的条目?

@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)

【问题讨论】:

    标签: python database mongodb discord bots


    【解决方案1】:

    我在很多不和谐机器人项目中都使用过 mongodb,最简单的方法是使用 $set 和 .update_one() 函数。如果您在此之后有任何问题,请不要犹豫回复!

    @bot.command()
    async def roll(ctx):
      ({"_id":(str(member)), "coinA":100, "coinB":50,"coinC":50,"coinD":50})
      user = mycol.find_one({'_id': ctx.message.author.id}) # we find the user we want, in this case the author of the cmd
      coinA = user["coinA"] # Here we store each individual coin in variables
      coinB = user["coinB"] 
      coinC = user["coinC"] 
      coinD = user["coinD"]
    
      coinAearn= random.randint(1,100) + coinA # add their current coin value
      coinBearn= random.randint(1,100) + coinB
      coinCearn= random.randint(1,100) + coinC
      coinDearn= random.randint(1,100) + coinD
      mycol.update_one({'_id': user}, {'$set': {'coinA': coinAearn}}) #update each coin with the new earnings
      mycol.update_one({'_id': user}, {'$set': {'coinB': coinBearn}}) #We use the $set to set the new value, 'coinB' to coinBearn.
      mycol.update_one({'_id': user}, {'$set': {'coinC': coinCearn}})
      mycol.update_one({'_id': user}, {'$set': {'coinD': coinDearn}})
    

    注意:这不是最理想的方法,您可以将其缩短很多,但我将其留作自己的追求..

    我的另一个提示是,当你注册一个新用户时,使用 member.id 来存储他们的“_id”值。

    【讨论】:

      猜你喜欢
      • 2016-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多