【问题标题】:pymongo insert_one() TypeError when inserting document with embedded documentspymongo insert_one() 插入带有嵌入文档的文档时出现类型错误
【发布时间】:2019-10-06 03:20:57
【问题描述】:

在我的脚本中,我尝试使用脚本中的 pymongo 插入一个文档。该文档还包含一个数组或嵌入的文档。直接在 Mongo 客户端中运行此代码时,它可以工作。从脚本来看它没有。

我将 MongoDB 4.08 与 pymongo 3.8.0 一起使用,并在 python 2.7.10 和 3.7.3 上进行了尝试。

这是我要插入的文档:

{'id': 84646995, 'first': 'AAA', 'last': 'YYY', 'email': 'AAA.YYY@domain.com', 'previous_cars': [{'make': 'BMW', 'model': 'model2'},{'make': 'Mercedes', 'model': 'model1'}]}

该脚本的目的是创建测试数据,一次一个文档,然后将其插入到集合用户中。

import pymongo
import random

client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.user # db user with a collection called user

first_names = ["AAA", "BBB", "CCC"]
last_names = ["XXX", "YYY", "ZZZ"]
make_list = ["Audi", "BMW", "Mercedes"]
model_list = ["model1", "model2", "model3"]
total = 0

for x in range(10):
    u_id = random.randint(10000000, 99999999)
    first = random.choice(first_names)
    last = random.choice(last_names)
    make1 = random.choice(make_list)
    make2 = random.choice(make_list)
    model1 = random.choice(model_list)
    model2 = random.choice(model_list)

    doc = "{'id': " + str(u_id) + ", 'first': '" + str(first) + "', 'last': '" + str(last) + "', 'email': '" + str(first) + "." + str(last) + "@firma.de', 'previous_cars': [{'make': '" + str(make1) + "', 'model': '" + str(model1) + "'},{'make': '" + str(make2) + "', 'model': '" + str(model2) + "'}]}"

    print(doc)

    db.user.insert_one(doc)
    total += 1

print("Done. Inserted " + str(total) + " documents.")

我得到的错误:

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

如果我将print(doc) 的输出粘贴到python shell(带有打开的pymongo 连接)中,我不会收到任何错误。非常感谢您的帮助。

【问题讨论】:

  • 您正在尝试插入一个字符串。将“{...”更改为 {'id'..
  • 太棒了,成功了。非常感谢。

标签: python json pymongo bson


【解决方案1】:

您当前遇到的错误消息基本上是让您知道您没有传递 dict 或任何受支持的数据结构。 - 为了让它工作,你需要改变:

doc = "{'id': " + str(u_id) + ", 'first': '" + str(first) + "', 'last': '" + str(last) + "', 'email': '" + str(first) + "." + str(last) + "@firma.de', 'previous_cars': [{'make': '" + str(make1) + "', 'model': '" + str(model1) + "'},{'make': '" + str(make2) + "', 'model': '" + str(model2) + "'}]}"

如下:

doc = {'id': str(u_id) ...}

【讨论】:

    猜你喜欢
    • 2014-01-17
    • 1970-01-01
    • 2023-03-08
    • 2015-09-27
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2018-03-30
    • 2011-02-15
    相关资源
    最近更新 更多