[英]How to check if the record exists in mongodb with python
我正在研究考勤系統。 這是我想檢查數據庫中是否存在具有該 ID 的員工的后端。 它似乎不是這樣工作的。 我正在向mongodb發送數據,每個emp都有不同的ID。 在添加新員工之前,我希望它檢查員工或記錄是否已經存在。
def checkEmployee(self):
"""
Check if employee exists with the ID.
Returns true if employee exists.
:rtype: object
:return:
"""
result = collection.find_one({"emp_id": self.emp_id})
# result is none means employee does not exist.
if result is None:
return False
return True
def addUser(self, first_name, last_name):
""" Add user to the database,
Employee is already initialized with an emp_id. Use this method to add it to the database.
"""
if self.checkEmployee() is True:
return "Employee Exists"
if collection.find_one({"emp_id": self.emp_id}) is None:
# Userdata to be added to database.
userData = {
"emp_id": self.emp_id,
"first_name": first_name,
"last_name": last_name
}
result = collection.insert_one(userData)
# If data is successfully updated, Returns True else Returns False .
if result.acknowledged:
return True
else:
return False
else:
print("Employee Already Exists with ID: ", self.emp_id)
由於您沒有將“_id”添加到 userData,它是由 MongoDB 自動生成的。 您可以使用“_id”字段來存儲您的員工 ID,因為“_id”在每個集合中始終是唯一的,您可以忽略以檢查文檔是否已存在,並直接使用更新操作和 upsert=True 選項,這將如果存在,則允許更新您的員工文檔,否則它只會將該文檔插入到數據庫中。
userData = {
"first_name": first_name,
"last_name": last_name
}
collection.upsert_one({ "_id": self.emp_id }, { "$set": userData }, upsert=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.