1,我们需要在自己的虚拟机中下载一个pymongo模块
在虚拟机终端中输入 pip install pymongo
查看我们下载的模块 pip list
2,连接数据库,并指定操作的数据库,以及操作的集合
class MyMongoDB: #创建一个类
def __init__(self, database, collection): #利用初始化的方法输入要操作的数据库(database),集合(collection)
import pymongo #导入pymongo模块
self.connet = pymongo.MongoClient() #连接到虚拟机上的mongo数据库
self.database = self.connet[database] #选择需要操作的数据库名称
self.collecttion = self.database[collection] #选择需要操作的集合名称(如果集合名不存在会自动创建)
3,向需要操作集合中插入数据
def insert(self, data, onlyone=True): #输入需要添加的数据(data),onlyone用来控制增加数据是单条还是多条
if onlyone: #控制数据为单条
self.collecttion.insert_one(data) #向集合中增加单条数据
else: #否则为多条数据
self.collecttion.insert_many(data) #向集合中增加多条数据
wl = MyMongoDB('stu', 'wl') #指定我们需要操作的数据库为stu数据库,需要操作的集合为wl集合
wl.insert([{
'name': 'cx', 'profession': 'bigdata', 'age': 18},
{
'name': 'fhb', 'profession': 'bigdata', 'age'