Pymongo 如何通过不插入来设置更新

Pymongo how to do set on update by not on insert

如果找到文档,我正在尝试更新文档,否则插入如下

upserts = [UpdateOne({"$and":[{'_id': x['_id']},{'time':{"$lt": x['time']}}]},
                     {'$setOnInsert': x, '$set':{'time':x['time']}},
                     upsert=True) for x in batch]
collection.bulk_write(upserts)

但是,我收到以下错误:

Updating the path 'time' would create a conflict at 'time'

我知道这是因为 time 密钥在 setsetOnInsert 中都得到了更新。我无法在 setOnInsert 中指定字段,因为键不固定。如果允许排除 setOnInsert 中的字段,那么我可以排除 time in that.

我该如何解决这个问题?

插入文档时,将处理 $set$setOnInsert 个文档。

查询执行器拒绝在一次更新中两次更新同一字段。

您可以尝试使用 dictionary comprehension 从 $setOnInsert 中删除时间字段,例如:

'$setOnInsert': {i:x[i] for i in x if i!='time'}