Skip to main content
 首页 » 编程设计

python之在 PyMongo 中,如果找到,如何获取文档的 _id,否则插入并获取插入文档的 _id

2025年05月04日16三少

例如:

我有一个收藏“故事” 其中每个文档的形式为:

{ 
  '_id': <default> 
  'story': <some very long string which should be unique in the collection> 
} 

现在每当我有一个故事时,如果它已经存在于“故事”中,我想要它的“_id”,否则插入一个带有“故事”字段集的新文档,并获取它的“_id”

我能想到的是:

story = "this is a very long story" 
id = stories_col.find_one_and_update({ 
    'story': story, 
}, { 
    'story': story, 
}, upsert=True, return_document=ReturnDocument.AFTER)['_id'] 

这不是很低效吗,因为它会更新(修改)文档,即使它不是必需的?这可以提高效率吗

请您参考如下方法:

你是那里的一部分,使用 $setOnInsert修改更新操作:

story = "this is a very long story" 
id = stories_col.find_one_and_update({ 
    'story': story, 
}, { 
    '$setOnInsert': { 'story': story } 
}, upsert=True, return_document=ReturnDocument.AFTER) 

这意味着如果文档匹配,那么将“没有实际”执行写入,因为这里唯一有效的操作是“插入”。

通常建议“始终”使用 update operators适合您的操作,因为您“总是”使用的“原始”对象会在没有它们的情况下替换文档中的“所有内容”。