将JSON文件导入MongoDB时,“TypeError:文档必须是dict的实例”

2024-04-24 15:27:04 发布

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

我想将一个JSON文件导入MongoDB,其结构如下:

{
  "a": 1,
  "aa": 1,
  "aaa": 1,
  "aah": 1,
  "aahed": 1,
  "aahing": 1,
  "aahs": 1,
  "aal": 1,
  "aalii": 1
}

但当我运行以下代码时:

def import_dictionary(collection):
    with open(dictionary, 'r', encoding='utf-8') as f:
        file_data = json.load(f)
        document = RawBSONDocument(BSON.encode(file_data))

    collection.insert_many(document)

我得到以下错误:

TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

我如何解决这个问题?提前谢谢


Tags: 文件jsondatadictionarymongodb结构documentcollection