如何使用python检查mongodb中是否存在记录
我正在研究考勤系统。这是我要检查数据库中是否存在具有该id的员工的后端。它似乎不是这样工作的。 我正在将数据发送到mongodb,每个emp都有不同的ID。在添加新员工之前,我希望它检查员工或记录是否已经存在如何使用python检查mongodb中是否存在记录,python,mongodb,Python,Mongodb,我正在研究考勤系统。这是我要检查数据库中是否存在具有该id的员工的后端。它似乎不是这样工作的。 我正在将数据发送到mongodb,每个emp都有不同的ID。在添加新员工之前,我希望它检查员工或记录是否已经存在 def checkEmployee(self): """ Check if employee exists with the ID. Returns true if employee exists. :rtype: object :return:
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”添加到用户数据,所以它是由MongoDB自动生成的。您可以使用“\u id”字段存储员工id,因为“\u id”在每个集合中始终是唯一的,您可以忽略它来检查文档是否已存在,并直接使用upsert=True选项和update操作,这将允许更新您的员工文档(如果它存在的话),否则只需将该文档插入数据库即可
userData = {
"first_name": first_name,
"last_name": last_name
}
collection.upsert_one({ "_id": self.emp_id }, { "$set": userData }, upsert=True)
为什么不在
emp\u id
上添加一个unique
索引,并处理inserterror
如果插入时收到dup\u key错误
,您可以将emp\u id
存储在\u id
中吗?@Messa组织内的每位员工都有一个单独的empID,根据他们的指定。所以在这里我有两个id,一个是emp_id,另一个是_id。这会有什么帮助呢?@HannanMustajab:如果你能提供一个示例文档,提供一些更详细的信息,这会很有帮助。@AbhinandanKothari{{{}id:{{$oid 5E0248721C9D44000001A2244},“emp_id:{$numberprint:“1234”},“名字”:“汉南”,“姓氏”:“穆斯塔贾布”,“惩罚”:[[“10/25/19”,“10/21/19”,“10/28/19”,“19]”],“休息日”:{“$numberprint”:“3”},“出席人数”:[{“日期”:“2019-10-20”,“地点”:“阿穆”,“时间”:“19:23:26”}]