rGu*_*Gun 1 python mongodb pymongo python-2.7
例如:
我有一个集合'故事',其中每个文档的形式如下:
{
'_id': <default>
'story': <some very long string which should be unique in the collection>
}
Run Code Online (Sandbox Code Playgroud)
现在每当我有一个故事时,如果它已经存在于'故事'中,我想要它的'_id',否则插入一个带有'story'字段集的新文档,并得到它的'_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']
Run Code Online (Sandbox Code Playgroud)
这不是效率低,因为它会更新(修改)文档,即使它不是必需的吗?这可以提高效率
你是那里的一部分,用于$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)
Run Code Online (Sandbox Code Playgroud)
这意味着如果文档匹配,那么将执行"无实际"写入,因为此处唯一有效的操作是"插入".
通常建议"始终"使用适合您的操作的更新操作符,因为您使用"始终"的"原始"对象将替换文档中的"所有内容"而不使用它们.
| 归档时间: |
|
| 查看次数: |
767 次 |
| 最近记录: |