简体   繁体   English

在使用pymongo在mongodb中使用upsert将查询更新为true后,如何返回记录字段?

[英]How to return field of record after update query with upsert as true in mongodb using pymongo?

I am trying to to insert record in mongodb but I dont want duplication so I am using update command with upsert=true 我试图在mongodb中插入记录,但是我不想重复,所以我在upsert=true时使用update命令

import pymongo
client = pymongo.MongoClient(settings.MONGO_DB_URI)
db = self.client[settings.MONGO_DB_NAME]
filter = {
    'my_id': '1234',
    'name': 'alok'
}
record = {
    'my_id': '1234',
    'name': 'alok',
    'marks': 26
}
status = db['mycollection'].update(filter, {'$setOnInsert': record}, upsert=True)  
print('id is ', status['my_id']) # this will not work but I want such behaviour

This code will insert record only if there is no existing record with matching filter values. 仅当不存在具有匹配过滤器值的记录时,此代码才会插入记录。 So there are two case: 因此有两种情况:
It will insert record 它将插入记录
It will not insert record if already exist 如果已经存在,则不会插入记录
In both the case I want to get my_id . 在两种情况下,我都想获取my_id How can I get my_id when update command execute? 执行更新命令时如何获取my_id?

您可以搜索文档,然后打印出其ID

print('id is ', db['mycollection'].find_one(filter)['my_id'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM