我读过,当我使用 pymongo 的 upsert 且不提供“_id”时,upsert 将尝试生成新的 Id,这将导致操作失败。这是真的?以及如何在不使用“_id”的情况下更新插入?
这是我使用 pymongo 的replace_one:
db['dataitemdetails'].replace_one({'asset_Id':tdata['asset_id'],'period_type':tdata['period_type'],'detail_id':tdata['detail_id'], 'currencycode':tdata['currencycode'],'dataitem_Id':tdata['dataitem_id'],'period_end':tdata['period_end'], 'scenario_id':tdata['scenario_id'],}, tdata, upsert=True)
Run Code Online (Sandbox Code Playgroud)
我创建了一个复合索引并使用我的搜索条件设置为唯一,这样在集合中我搜索的内容将始终是唯一的(如果存在)。
并使用replace_one我收到此错误:
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: finance.dataitemdetails index: asset_id_1_dataitem_id_1_detail_id_1_period_type_1_scenario_id_1_currencycode_1_period_end_1 dup key: { : 19, : 1211, : 0, : "Month", : 1, : "RC", : new Date(949276800000) }
Run Code Online (Sandbox Code Playgroud)
这是我使用相同过滤器查找的查询,它返回 1 个文档。
> db.dataitemdetails.find({'asset_id':19,'dataitem_id':1211,'detail_id':0,'period_type':'Month','currencycode':'RC','period_end':new Date(949276800000)})
{ "_id" : ObjectId("5c7721c17314e53a85be7e89"), "Value" : "USD", "period_end" : ISODate("2000-01-31T00:00:00Z"), "currencycode" : "RC", "scenario_id" : 1, "dataitem_id" : 1211, "period_type" : "Month", "detail_id" : 0, "asset_id" : 19 } …Run Code Online (Sandbox Code Playgroud)