如何将字符串转换为 BSON?
How to convert a string to BSON?
我有这样一个字符串:
document = '{ time : 14/09/19 16:00:00,
global : { full:190 , defects: 7 , btp: 6 , total: 202 } ,
domains : [ { domain : "A" , full:7 , defects: 2 , btp: 0 , total: 9 },
{ domain : "B" , full:0 , defects: 0 , btp: 0 , total: 0 },
{ domain : "C" , full:6 , defects: 0 , btp: 0 , total: 6 },
{ domain : "D" , full:26 , defects: 0 , btp: 2 , total: 28 },
{ domain : "E" , full:0 , defects: 0 , btp: 0 , total: 0 },
{ domain : "F" , full:4 , defects: 0 , btp: 2 , total: 6 },
{ domain : "G" , full:0 , defects: 0 , btp: 0 , total: 0 },
{ domain : "H" , full:21 , defects: 0 , btp: 1 , total: 22 },
{ domain : "I" , full:32 , defects: 0 , btp: 0 , total: 32 },
] }'
当我尝试将其插入 mongoDB 集合时,出现以下错误:
TypeError: 'str' object does not support item assignment
我不知道如何将字符串转换为 BSON,以便用它执行插入。
我查看了 bson_util
模块,但没有成功。
你很少需要自己直接处理BSON。这只是 mongo 用于在内部表示数据的格式。
作为数据库的用户或其客户端之一,您只需要处理 key:value
类型的 object 我们所说的文档。在python中,像object这样的key:value
最常见的是dict
object;一本字典。 您需要将该字符串转换为实际的 dict-like-object,然后再将其插入 mongo。
其中一个例子是使用 json
模块:
>>> import json
>>> document = json.loads('{ time : 14/09/19 16:00:00...')
您现在可以将 document
object 插入您的 collection。
这里重要的不是 BSON 部分。 MongoDB 驱动程序会处理这个问题。您的工作是将 JSON 转换为有效的 python 数据结构:
import json
data = json.loads(document)
collection.insert(data);
我有这样一个字符串:
document = '{ time : 14/09/19 16:00:00,
global : { full:190 , defects: 7 , btp: 6 , total: 202 } ,
domains : [ { domain : "A" , full:7 , defects: 2 , btp: 0 , total: 9 },
{ domain : "B" , full:0 , defects: 0 , btp: 0 , total: 0 },
{ domain : "C" , full:6 , defects: 0 , btp: 0 , total: 6 },
{ domain : "D" , full:26 , defects: 0 , btp: 2 , total: 28 },
{ domain : "E" , full:0 , defects: 0 , btp: 0 , total: 0 },
{ domain : "F" , full:4 , defects: 0 , btp: 2 , total: 6 },
{ domain : "G" , full:0 , defects: 0 , btp: 0 , total: 0 },
{ domain : "H" , full:21 , defects: 0 , btp: 1 , total: 22 },
{ domain : "I" , full:32 , defects: 0 , btp: 0 , total: 32 },
] }'
当我尝试将其插入 mongoDB 集合时,出现以下错误:
TypeError: 'str' object does not support item assignment
我不知道如何将字符串转换为 BSON,以便用它执行插入。
我查看了 bson_util
模块,但没有成功。
你很少需要自己直接处理BSON。这只是 mongo 用于在内部表示数据的格式。
作为数据库的用户或其客户端之一,您只需要处理 key:value
类型的 object 我们所说的文档。在python中,像object这样的key:value
最常见的是dict
object;一本字典。 您需要将该字符串转换为实际的 dict-like-object,然后再将其插入 mongo。
其中一个例子是使用 json
模块:
>>> import json
>>> document = json.loads('{ time : 14/09/19 16:00:00...')
您现在可以将 document
object 插入您的 collection。
这里重要的不是 BSON 部分。 MongoDB 驱动程序会处理这个问题。您的工作是将 JSON 转换为有效的 python 数据结构:
import json
data = json.loads(document)
collection.insert(data);