bson.errors.InvalidDocument:使用json时,键'$ numberDecimal'不能以'$'开头

问题描述 投票:1回答:1

我有一个小的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:键'$ numberDecimal'不能以'$'开头。

我目前正在使用python加载json。这是代码:

import os,sys
import re
import io
import json
from pymongo import MongoClient

#connection
client = MongoClient('localhost',27018)
db     = client['myDB']
coll   = db['test_dec']                                                                                                 

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 = json.load(f)
            coll.insert(doc_data)

client.close()

我正在使用json文件。如果我尝试解析Decimal128('2.33')之类的内容,则输出为“ ValueError:无法解码JSON对象”,因为我的json格式无效。

有什么建议吗?

谢谢

python json mongodb bson
1个回答
0
投票

如果要尝试将extended json文件加载到应用程序中并使用pymongo插入其内容,则需要将文件加载为extended json,而不仅仅是json。

尝试this

© www.soinside.com 2019 - 2024. All rights reserved.