繁体   English   中英

如何使用python检查mongodb中是否存在记录

[英]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.

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