Pymongo:insert_many()为dicts列表提供“TypeError:document必须是dict的实例”

时间:2018-06-15 08:32:12

标签: pymongo python-3.6

谷歌搜索时我无法找到任何相关解决方案,所以我想我会在这里试试。

我有一个程序,我通过文件夹解析某种跟踪文件,然后将它们保存在MongoDB数据库中。像这样:

posts = function(source_path)
client = pymongo.MongoClient()
db = client.database
collection = db.collection
insert = collection.insert_many(posts)

def function(...):
    ....
    post = parse(trace)
    posts.append(post)
    return posts

def parse(...):
    ....
    post = {'Thing1': thing,
            'Thing2': other_thing,
            etc}
    return post

然而,当我进入“insert = collection.insert_many(posts)”时,它会返回错误:

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

根据调试器,“posts”是一个大约1000个dicts的列表,根据我的所有研究,它应该是vaild输入。如果我构造一个较小的dicts列表和insert_many(),它可以完美地工作。

有谁知道这个问题是什么?

1 个答案:

答案 0 :(得分:0)

更多调试显示问题是"解析"函数有时返回None而不是dict。轻松修复。