MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。
首先下载pymongo包:
sudo apt-get update
sudo apt install python3-pip
python3 -m pip install pymongo
2.创建python文件,命名为pyinsert.py
3.在pyinsert.py中编写如下代码:
from pymongo import MongoClient
from random import randint
name1 = ["yang ", "li ", "zhou "]
name2 = [
"chao",
"hao",
"gao",
"qi gao",
"hao hao",
"gao gao",
"chao hao",
"ji gao",
"ji hao",
"li gao",
"li hao",
]
provinces = [
"guang dong",
"guang xi",
"shan dong",
"shan xi",
"he nan"
]
client = MongoClient('localhost', 27017)
db = client.student
sm = db.smessage
sm.remove()
for i in range(1, 100):
name = name1[randint(0, 2)] + name2[randint(0, 10)]
province = provinces[randint(0, 4)]
new_student = {
"name": name,
"age": randint(1, 30),
"province": province,
"subject": [
{"name": "chinese", "score": randint(0, 100)},
{"name": "math", "score": randint(0, 100)},
{"name": "english", "score": randint(0, 100)},
{"name": "chemic", "score": randint(0, 100)},
]}
print(new_student)
sm.insert_one(new_student)
print(sm.count())
执行py代码
切换至pyinsert.py所在目录下,执行以下命令:
python3 pyinsert.py
查看插入的数据
use student
db.smessage.findOne()