Pymongo BulkWriterResult不包含upserted_ID

2024-05-15 08:37:11 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,现在我正在尝试使用pymongo在本地mongodb中插入一些东西。(我检查文档是否在db中,如果在db中,则更新它,否则只需插入它)

我正在使用bulk_write来做这件事,一切都正常。数据被插入/更新

但是,我需要新插入/更新的文档的ID,但是bulkWriteResult对象中的“upserted_ID”是空的,即使它声明插入了14个文档

我添加了这个带有变量的屏幕截图。是虫子吗?还是有什么我不知道的

debug_screenshot

最后,有没有一种方法可以在不在数据库中实际搜索的情况下获取文档的ID?(如果可能,我更愿意使用批量写入)

谢谢你抽出时间

编辑: 正如建议的那样,我添加了代码的一部分,以便更容易获得一般的想法:

for name in input_list:
    if name not in stored_names: #completely new entry (both name and package)
        operations.append(InsertOne({"name": name, "package" : [package_name]}))

if len(operations) == 0:
    print ("## No new permissions to insert")
    return
bulkWriteResult = _db_insert_bulk(collection_name,operations)

和插入功能:

def _db_insert_bulk(collection_name,operations_list):
    return db[collection_name].bulk_write(operations_list) 

Tags: namein文档idpackagenewdbif
2条回答

此功能是crud specification的一部分,应该由兼容的驱动程序(包括pymongo)实现。请参考pymongo文档以了解正确用法

Ruby中的示例:

irb(main):003:0> c.bulk_write([insert_one:{a:1}])
=> #<Mongo::BulkWrite::Result:0x00005579c42d7dd0 @results={"n_inserted"=>1, "n"=>1, "inserted_ids"=>[BSON::ObjectId('5fb7e4b12c97a60f255eb590')]}>

您的输出显示零个文档被上传,因此不会有任何ID与上传的文档关联

您的代码似乎根本没有显示任何upserts,这再次意味着您将看不到任何upserts id

pymongoBulkWriteResult中的upserted_ids字段仅包含作为upsert操作的一部分插入的记录的ID,例如设置了upsert=True参数的UpdateOneReplaceOne

当您正在执行没有upsert选项的InsertOne时,upserted_ids列表将为空

pymongo的BulkWriter中缺少inserted_ids字段,导致驱动程序中出现遗漏;从技术上讲,它符合D.SM回答中提到的crud规范,因为它被注释为“驾驶员可能选择不提供此属性”

但是。。。有一个答案。如果您仅在批量更新中执行插入操作(而不是混合批量操作),只需使用insert_many()。它与大容量写入一样高效,而且至关重要的是,它确实在InsertManyResult对象中提供了inserted_ids

from pymongo import MongoClient

db = MongoClient()['mydatabase']

inserts = [{'foo': 'bar'}]

result = db.test.insert_many(inserts, ordered=False)
print(result.inserted_ids)

印刷品:

[ObjectId('5fb92cafbe8be8a43bd1bde0')]

相关问题 更多 >