我目前正在尝试编写一个脚本,将文档插入 MongoDb 并返回每个元素的存储位置。非常简单,感谢 insert_many()
,但是如果我在插入时出现错误,我的问题就会出现。
我将无法获取刚刚插入的 ID。
from pymongo import MongoClient
client = MongoClient(...)
db = client.test
r = db.test.insert_many([{'foo': 1}, {'foo': 2}, {'foo': 3}])
r.inserted_ids
#: [ObjectId('56b2a592dfcce9001a6efff8'),
#: ObjectId('56b2a592dfcce9001a6efff9'),
#: ObjectId('56b2a592dfcce9001a6efffa')]
list(db.test.find())
#: [{'_id': ObjectId('56b2a592dfcce9001a6efff8'), 'foo': 1},
#: {'_id': ObjectId('56b2a592dfcce9001a6efff9'), 'foo': 2},
#: {'_id': ObjectId('56b2a592dfcce9001a6efffa'), 'foo': 3}]
# This is dead stupid, but forcing an error by re-using the ObjectId we just generated
r2 = db.test.insert_many([{'foo': 4}, {'_id': r.inserted_ids[0], 'foo': 6}, {'foo': 7}])
#: ---------------------------------------------------------------------------
#: BulkWriteError Traceback (most recent call last)
#: <Cut in the interest of time>
当然,r2
没有初始化,所以我不能要求inserted_ids
,但是,数据库中已经插入了一条记录:
list(db.test.find())
#: [{'_id': ObjectId('56b2a592dfcce9001a6efff8'), 'foo': 1},
#: {'_id': ObjectId('56b2a592dfcce9001a6efff9'), 'foo': 2},
#: {'_id': ObjectId('56b2a592dfcce9001a6efffa'), 'foo': 3},
#: {'_id': ObjectId('56b2a61cdfcce9001a6efffd'), 'foo': 4}]
我想要的是能够可靠地找出按顺序插入的 ID。类似的东西:
r2.inserted_ids
#: [ObjectId('56b2a61cdfcce9001a6efffd'),
#: None, # or maybe even some specific error for this point.
#: None]
设置 ordered=False
仍然会出现错误,因此 r2
不会被初始化,(而且它不会按照我给出的顺序可靠地返回 id) .
这里有什么选项吗?
最佳答案
pymongo sets the _id
field at client side , 在将其发送到服务器之前。它会修改您就地传递的文档。
这意味着您传递的所有文档都保留了 _id
字段集——成功的和失败的。
所以你只需要弄清楚哪些是成功的。这可以像@Austin 解释的那样完成。
类似于:
docs = [{'foo': 1}, {'foo': 2}, {'foo': 3}]
try:
r = db.test.insert_many(docs)
except pymongo.errors.OperationFailure as exc:
inserted_ids = [ doc['_id'] for doc in docs if not is_failed(doc, exc) ]
else:
inserted_ids = r.inserted_ids
is_failed(doc, exc)
可以通过在异常详细信息中的失败文档列表中搜索 doc
来实现,如@Austin 所解释的。
关于mongodb - 在 insert_many() 失败后获取插入的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35191042/