MongoDB不允许在键中使用“.”

2024-05-23 17:33:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试图保存一个字典,其中包含MongoDB的关键部分中的特殊字符“.”。下面显示的错误清楚地表明密钥不能包含特殊字符“.”。

>>> import pymongo
>>> client = pymongo.MongoClient('localhost')
>>> db = client['malware']                                                                                                                                                          
>>> test = db['test']
>>> d = {'.aaa' : '.bbb'}                                                                                                                                                           
>>> test.insert(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/site-packages/pymongo/collection.py", line 362, in insert
    self.database.connection)
bson.errors.InvalidDocument: key '.aaa' must not contain '.'

但我当前的信息在数据的关键部分包含“.”,我需要将其存储到MongoDB。目前我正在删除字符串中的“.”,另一个选项是用“\u”或其他特殊字符替换它。

然而,所有这些都会导致信息丢失,因为如果我有一个键“.a a a”和一个键“aaa”,并且如果我将“.”转换为“”,那么这些键完全相同,我会丢失一些信息。为什么Mongo不允许我将“.aaa”保存到数据库中?

有什么办法解决这个问题吗?


Tags: intestclient信息db字典mongodb错误
2条回答

根据source,可以将check_keys设置为False:

 test.insert(d,check_keys=False)


 def insert(self, doc_or_docs, manipulate=True,
           safe=None, check_keys=True, continue_on_error=False, **kwargs):

它确实有效:

In [28]: d = {'.aaa' : '.bbb'}

In [29]: test.insert(d,check_keys=False)
Out[29]: ObjectId('54ea604bf9664e211e8ed4e6')

docstring声明:

  • check_keys (optional): If True check if keys start with '$' or contain '.', raising :class:~pymongo.errors.InvalidName in either case.

您似乎可以使用除两个$.之外的任何字符,因此前导下划线或任何其他字符都很好,可能是更好的选择。

常见问题解答中有关于escaping 的信息:

In some cases, you may wish to build a BSON object with a user-provided key. In these situations, keys will need to substitute the reserved $ and . characters. Any character is sufficient, but consider using the Unicode full width equivalents: U+FF04 (i.e. “$”) and U+FF0E (i.e. “.”).

点符号faq解释了为什么使用.不是一个好主意:

MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document. To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes:

不能使用“.aaa”作为密钥,因为Mongo使用点来引用nested documents

如果要使键看起来像点,可以使用类似于\u002E的unicode等效键:

>>> d = {'\u002Eaaa' : '\u002Ebbb'}    

不过,我建议你选择另一个角色并接受它作为平台的“限制”。

相关问题 更多 >