首页 > 解决方案 > 插入包含 `.` 的值时出现 MongoDB 错误

问题描述

{'question1.': 'no', 'question2.': 'no.'}
Future exception was never retrieved
future: <Future finished exception=InvalidDocument("key 'question1.' must not contain '.'")>
        print(answers)
        self.client.applicants.insert_one(
            {
                "name": args,
                "userId": ctx.author.id,
                "guildId": ctx.guild.id,
                "questions": answers,
                "messageId": application_message.id,
            }
        )

嘿。我正在尝试将其插入到我的 MongoDB 数据库中。但是,我收到上面的错误,上面说问题不能包含.。我怎样才能解决这个问题而不必从问题中删除标点符号?因为拥有这个将是理想的。

标签: pythonmongodb

解决方案


简短的回答:你不能。

在 MongoDB 版本 <= 3.6 中可以选择使用该选项完全绕过验证check_keys=False。但从那以后,这个选项就被弃用了。

尽管 MongoDB 有较新的版本,但出于显而易见的原因bypass_document_validation=True,它不会绕过该字符。.

在 JIRA (SERVER-30575)上有一个未解决的问题,它仍然是开放的。此外,PyMongo与此相关的具体问题曾在PYTHON-1522中提出。

因此,在SERVER-30575问题修复之前,您别无选择。

我建议您重新安排架构设计,将键名作为值嵌入到不同的键中。

像这样的东西:

question = [
    {
        "question": "question1.",
        "answer": "no.",
    },
    {
        "question": "question2.",
        "answer": "yes.",
    },
]

推荐阅读