我目前正在尝试编写一个脚本,该脚本将文档插入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在将_id
字段发送到服务器之前在客户端设置该字段。它会修改你传递文件的地方。
这意味着您传递的所有文档都保留有_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所述。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句