簡體   English   中英

如何更新 mongoDB 中特定嵌套字典中的項目

[英]How do I update an item in a specific nested dictionary in mongoDB

我有 3 個字典在線存儲在 MongoDB 中,我想訪問特定字典中的特定項目並用不同的項目更新它,但我不知道該怎么做。 我嘗試了多種方法,但似乎都沒有奏效。 我不想通過字典的索引訪問字典中的項目,因為會有更多的字典,而且我每次都需要編輯代碼。 我試圖用這段代碼更新它,但是它不起作用。 有誰知道這個問題的解決方案?

@client.command()
async def warn(ctx, user: discord.User, reason: Optional[str] = None):
    await ctx.message.delete()
    guild_id = ctx.guild.id
    warn_id = f"{uid.uuid1()}"  # Randomly generated warning ID
    if reason is None:
        reason = "No reason given!"  # reason
    warn_count = 1
    for i in role_ids:
        if role_ids[i]["_id"] == ctx.guild.id:
            for _user in range(0, len(role_ids[i]["logs"]["warn_logs"]["users"])):
                # if role_ids[i]["logs"]["warn_logs"]["users"][_user]:
                if f"{user.id}" in role_ids[i]["logs"]["warn_logs"]["users"][_user]:
                    for e in range(0, len(role_ids[i]["logs"]["warn_logs"]["users"][_user][f"{user.id}"]["warnings"])):
                        if f"warning_{warn_count}" in \
                                role_ids[i]["logs"]["warn_logs"]["users"][_user][f"{user.id}"]["warnings"][e]:
                            warn_count += 1
                            pass
                        else:
                            # role_ids[i]["logs"]["warn_logs"]["users"][_user][f"{user.id}"]["warnings"][e+1]
                            my_dict = {"$set": {
                                f"warning_{warn_count}": {"author": f"{ctx.author.id}",
                                                          "reason": reason,
                                                          "warn_id": warn_id},
                                "warning_0":""}}
                            mongo_col.find_one_and_update({"_id": ctx.guild.id, "logs": {
                                "warn_logs": {"users": [{f"{user.id}": {"warnings": [{"warning_0": ""}]}}]}}}, my_dict)

字典和我要訪問的項目。

所以我找不到解決問題的方法,但我能夠想到一種替代方法,它可能效率不高,但效果很好。 我從 mongodb 集合中取出所有數據並將其保存在本地字典變量中,然后使用本地變量搜索/編輯數據並使用“update_one”方法將其發布回 mongodb。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM