MongoDB开发员工信息管理系统

最近在看谢乾坤老师的《左手MongoDB,右手Redis》,我会将书中的代码都敲一遍,代码放在CSDN挺方便的:

一、插入数据

import random, time
from pymongo import MongoClient

name = ["李小一", "诸葛小二", "南宫小三", "朱小四", "朱小六", "诸葛小七", "慕容小八", "南宫小九", "夏侯小十", "朱十一", "诸葛十二", "赵十三", "夏侯十四", "王十五",
        "夏侯十六", "夏侯十七", "诸葛十八", "南宫十九", "夏侯二十"]
age = [24, 20, 22, 13, 23, 30, 26, 15, 20, 30, 26, 15, 28, 21, 12, 10, 17, 22, 19]
birthday = [str(time.localtime().tm_year - age[i]) + "-" + str("{:02d}".format(random.randint(1, 12))) + "-" + str(
    "{:02d}".format(random.randint(1, 28)))
            for i in range(19)]
origin_home = ["河北邯郸", "陕西西安", "北京", "天津", "广东广州", "山东济南", "天津", "湖北武汉", "广东广州", "北京", "河南郑州", "河北邯郸", "贵州贵阳", "贵州贵阳",
               "天津", "北京", "广东广州", "陕西西安", "天津"]
current_home = [origin_home[random.randint(0, 18)] for i in range(19)]

client = MongoClient('mongodb://localhost:27017')
database = client.chapter_4
collection = database.people_info
for i in range(19):
    result = collection.insert_one({
        'id': i + 1,
        'name': name[i],
        'age': age[i],
        'birthday': birthday[i],
        "origin_home": origin_home[i],
        "current_home": current_home[i],
        "deleted": 0
    })
    print(i, result)

运行截图:
在这里插入图片描述

二、DataBaseManager

    def __init__(self):
        """
        你需要在这里初始化MongoDB的连接,连上本地MongoDB,库名为chapter_4,集合名为people_info
        """
        client = MongoClient("mongodb://127.0.0.1:27017")
        database = client.chapter_4
        self.handler = database.people_info
    def query_info(self):
        """
        你需要在这里实现这个方法,
        查询集合people_info并返回所有"deleted"字段为0的数据。
        注意返回的信息需要去掉_id
        """
        info_list = list(self.handler.find({'deleted': 0}, {'_id': 0}))
        return info_lis

在这里插入图片描述

    def _query_last_id(self):
        """
        你需要实现这个方法,查询当前已有数据里面最新的id是多少
        返回一个数字,如果集合里面至少有一条数据,那么就返回最新数据的id,
        如果集合里面没有数据,那么就返回0
        提示:id不重复,每次加1

        :return: 最新ID
        """
        # 查询最新的ID
        the_id = self.handler.find({}, {"id": 1}).sort('id',-1).limit(1)[0]['id']
        return the_id if the_id else 0
    def add_info(self, para_dict):
        """
        你需要实现这个方法,添加人员信息。
        你可以假设para_dict已经是格式化好的数据了,
        你直接把它插入MongoDB即可,不需要做有效性判断。

        在实现这个方法时,你需要首先查询MongoDB,获取已有数据里面最新的ID是多少,
        这个新增的人员的ID需要在已有的ID基础上加1.


        :param para_dict: 格式为{'name': 'xxx', 'age': 12, 'birthday': '2000-01-01', 'origin_home': 'xxx', 'current_home': 'yyy', 'deleted': 0}
        :return: True或者False
        """
        para_dict['id'] = self._query_last_id()+1
        try:
            self.handler.insert_one(para_dict)
        except Exception as e:
            print(f"错误信息:{e}")
            return False
        return True
    def update_info(self, people_id, para_dict):
        """
        你需要实现这个方法。这个方法用来更新人员信息。
        更新信息是根据people_id来查找的,因此people_id是必需的。

        :param people_id: 人员id,数字
        :param para_dict: 格式为{'name': 'xxx', 'age': 12, 'birthday': '2000-01-01', 'origin_home': 'xxx', 'current_home': 'yyy'}
        :return: True或者False
        """
        try:
            self.handler.update_one({'id':people_id},{'$set':para_dict})
        except Exception as e:
            print(f"错误信息:{e}")
            return False
        return True

注意学习这种思想:

    def del_info(self, people_id):
        """
        你需要实现这个方法。请注意,此处需要使用"假删除",
        把删除操作写为更新"deleted"字段的值为1
        :param people_id: 人员id
        :return: True或者False
        """
        self.update_info(people_id, {'deleted':1})

在这里插入图片描述

  • 2
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值