先查询, 如果存在 则更新;如果不存在 则插入。
import pymongo
def insert_to_db(data, switch_id, route_id):
myclient = pymongo.MongoClient("mongodb://1.1.1.1:27017/")
mydb = myclient["test"]
mydb.authenticate("abc","xxxxxx")
mycol = mydb["tt"]
existing_data = mycol.find_one({'sport.Name': sport_id, 'sport.b.id': b_id}) # 查询
logging.info("existing_data: {}".format(existing_data))
if existing_data:
info = existing_data['sport']['b']['c']
for key, value in info.items():
if key not in data['sport']['b']['c'].keys():
data['sport']['b']['c'][key] = value
mycol.update_one(existing_data, {"$set": data}, upsert=True) # 更新
else:
mycol.insert_one(data) # 插入