【问题标题】:Pymongo: insert_many() gives "TypeError: document must be instance of dict" for list of dictsPymongo:insert_many() 为字典列表提供“TypeError:文档必须是字典的实例”
【发布时间】:2018-11-25 01:51:25
【问题描述】:

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

我有一个程序,我通过文件夹解析某种跟踪文件,然后将它们保存在 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 列表和 insert_many(),它可以完美地工作。

有人知道问题出在哪里吗?

【问题讨论】:

    标签: pymongo python-3.6


    【解决方案1】:

    更多的调试发现问题是“解析”函数有时返回 None 而不是 dict。轻松修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2019-05-08
      相关资源
      最近更新 更多