[英]pymongo update_one(), upsert=True without using $ operators
[英]How to return field of record after update query with upsert as true in mongodb using pymongo?
我试图在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
仅当不存在具有匹配过滤器值的记录时,此代码才会插入记录。 因此有两种情况:
它将插入记录
如果已经存在,则不会插入记录
在两种情况下,我都想获取my_id
。 执行更新命令时如何获取my_id?
您可以搜索文档,然后打印出其ID
print('id is ', db['mycollection'].find_one(filter)['my_id'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.