【发布时间】:2020-04-29 10:08:27
【问题描述】:
我有一个小的 json 文件,包含以下几行:
{
"IdTitulo": "Jaws",
"IdDirector": "Steven Spielberg",
"IdNumber": 8,
"IdDecimal": "2.33"
}
我的数据库集合中有一个模式,名为 test_dec。这是我用来创建架构的:
db.createCollection("test_dec",
{validator: {
$jsonSchema: {
bsonType: "object",
required: ["IdTitulo","IdDirector"],
properties: {
IdTitulo: {
"bsonType": "string",
"description": "string type, nombre de la pelicula"
},
IdDirector: {
"bsonType": "string",
"description": "string type, nombre del director"
},
IdNumber : {
"bsonType": "int",
"description": "number type to test"
},
IdDecimal : {
"bsonType": "decimal",
"description": "decimal type"
}
}
}}
})
我已多次尝试插入数据。问题出在 IdDecimal 字段值中。
一些试验,将 IdDecimal 行替换为:
"IdDecimal": 2.33
"IdDecimal": {"$numberDecimal": "2.33"}
"IdDecimal": NumberDecimal("2.33")
它们都不起作用。第二个是MongoDB手册(mongodb-extended-json)提供的正式解决方案,错误是我在我的问题中放置的输出: bson.errors.InvalidDocument: key'$numberDecimal' must not start with '$' .
我目前正在使用 python 来加载 json。我一直在玩这个文件:
import os,sys
import re
import io
import json
from pymongo import MongoClient
from bson.raw_bson import RawBSONDocument
from bson.json_util import CANONICAL_JSON_OPTIONS,dumps,loads
import bsonjs as bs
#connection
client = MongoClient('localhost',27018,document_class=RawBSONDocument)
db = client['myDB']
coll = db['test_dec']
other_col = db['free']
for fname in os.listdir('/mnt/win/load'):
num = re.findall("\d+", fname)
if num:
with io.open(fname, encoding="ISO-8859-1") as f:
doc_data = loads(dumps(f,json_options=CANONICAL_JSON_OPTIONS))
print(doc_data)
test = '{"idTitulo":"La pelicula","idRelease":2019}'
raw_bson = bs.loads(test)
load_raw = RawBSONDocument(raw_bson)
db.other_col.insert_one(load_raw)
client.close()
我正在使用 json 文件。如果我尝试解析 Decimal128('2.33') 之类的内容,则输出为“ValueError: No JSON object could be decoded”,因为我的 json 格式无效。
结果
db.other_col.insert_one(load_raw)
是不是插入了“test”的内容。 但我不能将 doc_data 与 RawBSONDocument 一起使用,因为它就是这样。它说:
TypeError: unpack_from() argument 1 must be string or buffer, not list:
当我设法将 json 直接解析为 RawBSONDocument 时,我得到了所有的垃圾,并且数据库中的记录看起来像这里的示例:
{
"_id" : ObjectId("5eb2920a34eea737626667c2"),
"0" : "{\n",
"1" : "\t\"IdTitulo\": \"Gremlins\",\n",
"2" : "\t\"IdDirector\": \"Joe Dante\",\n",
"3" : "\t\"IdNumber\": 6,\n",
"4" : "\"IdDate\": {\"$date\": \"2010-06-18T:00.12:00Z\"}\t\n",
"5" : "}\n"
}
似乎将扩展的 json 加载到 MongoDB 中并不是那么简单。扩展版是因为我想使用架构验证。
Oleg 指出它是 numberDecimal 而不是 NumberDecimal,因为我以前有它。我已经修复了 json 文件,但没有任何改变。
执行:
with io.open(fname, encoding="ISO-8859-1") as f:
doc_data = json.load(f)
coll.insert(doc_data)
还有json文件:
{
"IdTitulo": "Gremlins",
"IdDirector": "Joe Dante",
"IdNumber": 6,
"IdDecimal": {"$numberDecimal": "3.45"}
}
【问题讨论】:
-
这能回答你的问题吗? Python - Pymongo MongoDB 3.4 - NumberDecimal
-
没有。我正在使用一个json。如果我尝试将 IdDecimal 替换为 Decimal128("2.33") 错误状态:“ValueError: No JSON object could be decoded”