二级标题单对单表关联:
开始先循环插入数据到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中打印的数据: