mongodb - 在 insert_many() 失败后获取插入的 ID

标签 mongodb python-3.x pymongo

我目前正在尝试编写一个脚本,将文档插入 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/

相关文章:

python - 在 python3 中从 bash 执行 DNS 查询的最佳方法是什么?

MongoDB查询仅返回嵌入文档

java - 需要在 spring mongotemplate 中复制查询

javascript - 使用 PUT 和 update() Mongoose 增加 JSON 字段

node.js - 如何使用 MongoDB 按名字和姓氏搜索用户?

python - 为什么 getter/setter 方法必须与原始属性的名称相同?

python - 使用 Turtle 在 Python 中出现错误颜色字符串错误

python - MongoDB 中的 Mod 运算符

python - 在 Pymongo 中实例化 Connection() 对象的适当范围

python - 使用 Pymongo 从 Windows 连接到 AWS 实例上的 MongoDB