• Python Django 循环插入到 MongoDB数据库中


     单对单表关联:

    开始先循环插入数据到MongoDB中,然后把表1的ID放到表2中,然后就可以通过表2来查看表1了

    import random
    import pymongo
    '''DBRef关联的表'''
    from bson.dbref import DBRef
    from django.http import HttpResponse
    from bson.objectid import ObjectId
    
    
    def Circular_Insertion(request):
        # 链接mongo
        client = pymongo.MongoClient("127.0.0.1:27017")
        # mongo 数据库名字
        db = client.Chen
    
        cursor1 = db.zhan1.find({})
        cursor2 = db.zhan2.find({})
    
        '''循环插入到数据库的表中'''
        # 姓
        first_name = ["赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
                      "何", "吕", "施", "张"]
        # 循环插入的数量
        for i in range(3):
            first=random.sample(first_name,1)
            # 名  随机一万个字符
            last_names = chr(random.randint(0x4e00, 0x9fbf))
            name=first[0]+last_names
            # 成绩
            score1 = random.randint(0, 100)
            score2 = random.randint(0, 100)
            score3 = random.randint(0, 100)
            # 插入到数据库中的zhan1表中
            db.zhan1.insert_many([{'names': name, 'Subject': {"score1":score1,"score2":score2,"score3":score3,}}])
        # 遍历zhan1表
        for cur in cursor1:
            # 遍历zhan1表中的"_id"
            str1 = (cur["_id"])
            # 打印zhan1表
            print(cur)
            # 循环插入的数量
            for i in range(3):
                # 电话
                phone=('13' + str(random.randrange(4, 10)) + ''.join(str(random.choice(range(10))) for _ in range(8)))
                # 班级
                grade = random.randint(1, 3)
                # 年龄
                age = random.randint(1, 100)
                # 插入到数据库中的zhan2的表
                db.zhan2.insert_many([{'ref':DBRef(collection="zhan1",id=str1),'grades': grade,'ages': age,'phones': phone}])
                break
    
        print('-'*200)
        # 通过zhan2打印zhan1的信息
        for j in cursor2:
            show = db[j['ref'].collection].find({"_id": ObjectId(j['ref'].id)})
            for pt in show:
                print(pt)
                break
            print(j)
        return HttpResponse("数据插入成功!")

     打印的数据:

    在mongo的cmd中打印的数据: 

    永远的新手
  • 相关阅读:
    ubuntu中,update,upgrade出现问题总结
    Xshell7连接kali linux(2021.9.13)
    pycharm安装igraph,简单实例(2021.8.21)
    mininet可视化(2021.6.25)
    冷知识:你会搜索信息吗
    论文写作注意事项
    onenote2016怎么自动备份笔记本到本地?
    Cbench、Scapy、sflow、iperf——学习中
    Zookeeper、Docker——学习中
    OpenStack管理、KVM、ClouldSim部署——学习中
  • 原文地址:https://www.cnblogs.com/chenzhanxu/p/14771612.html
Copyright © 2020-2023  润新知