Pymongo insert_many 批量写入错误

6
我将尝试将名为posts的以下字典列表插入到Mongo中,但出现了一个BulkWriteError: batch op errors occurred错误,我不知道如何解决。

posts:

[{'#AUTHID': 'fffafe151f07a30a0ede2038a897b680',
  'Records': [
   {'DATE': '07/22/09 05:54 PM',
    'STATUS': 'Is flying back friday night in time to move the rest of his stuff then go to work the next morning... great.'},
    ......

   {'DATE': '07/19/09 04:39 PM', 'STATUS': 'is stealing his net by the lake'}]},

 {'#AUTHID': 'fffafe151f07a30a0ede2038a897b680',
  'Records': [
   {'DATE': '07/22/09 05:54 PM',
    'STATUS': 'Is flying back friday night in time to move the rest of his stuff then go to work the next morning... great.'},
   {'DATE': '07/19/09 04:39 PM', 'STATUS': 'is stealing his net by the lake'},
  ....

我使用的代码是:
collection = db.posts
collection.insert_many(p for p in posts )

但是后来我遇到了一个错误,显示为 BulkWriteError:批处理操作错误,只成功导入了第一个字典(对应于第一个#AUTHID)。
我找到了一个链接,描述了类似的情况,但并没有解释这种情况发生的原因或如何解决此问题。该链接在以下位置的_Why does PyMongo add an id field to all of my documents?下:
https://github.com/mongodb/mongo-python-driver/blob/master/doc/faq.rst#id25

根据您提供的上述示例“posts”,似乎该文档是重复的,因为内容相同。请注意,常见问题解答中指出,应将单个文档插入为多个文档。我怀疑您的“dict(s)”是同一实例。 - CallMeLaNN
2个回答

1
不晚回答,你已经接近成功了。我不确定FAQ是否已更新,请仔细阅读:
调用insert_many()时,如果使用单个文档的引用列表,则会引发BulkWriteError。
请注意,它说“单个”或换句话说,“相同的实例”。FAQ中的示例展示了如何使用相同实例产生错误。您可以通过使用id()来显示内存地址来检查是否相同。实际上,我可以看到您的文档内容是相同的。很可能(但不一定)是同一个实例。
print id(posts[0])
print id(posts[1])

如果字典中有相同的实例,那么在准备posts变量时可能会出现问题。请确保所有列表项都具有不同的实例,因为您正在插入(许多)不同的文档!

0

这里是输出 在这个输出中,存储了列表中的记录。

from pymongo import MongoClient 
client = MongoClient('localhost', 27017)
db = client['post']
posts = [{'#AUTHID': 'fffafe151f07a30a0ede2038a897b680',
    'Records': [
        {'DATE': '07/22/09 05:54 PM',
            'STATUS': 'Is flying back friday night in time to move the rest of his stuff then go to work the next morning... great.'},


        {'DATE': '07/19/09 04:39 PM', 'STATUS': 'is stealing his net by the lake'}]},

    {'#AUTHID': 'fffafe151f07a30a0ede2038a897b680',
        'Records': [
        {'DATE': '07/22/09 05:54 PM',
        'STATUS': 'Is flying back friday night in time to move the rest of his stuff then go to work the next morning... great.'},
        {'DATE': '07/19/09 04:39 PM', 'STATUS': 'is stealing his net by the lake'}]}]
collection = db.posti.insert_many(p for p in posts )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接