目录

 

一、环境准备

1、python3安装

2、MongoDB4安装

二、安装驱动

1、pip在线安装pymogo驱动

2、pymogo驱动测试

三、连接脚本

1、脚本编写

2、命令行查看结果


一、环境准备

1、python3安装

windows离线安装python3.6.8环境:https://blog.csdn.net/qq262593421/article/details/111309116

2、MongoDB4安装

Linux 离线安装 python 3.6.10:https://blog.csdn.net/qq262593421/article/details/105395101

win10安装MongoDB4.4:https://blog.csdn.net/qq262593421/article/details/114277083

二、安装驱动

1、pip在线安装pymogo驱动

pip install pymongo

2、pymogo驱动测试

python
import pymongo

三、连接脚本

1、脚本编写

MongoDBConn.py

import pymongo

"""客户端连接"""
def db_client(ip="127.0.0.1",port="27017"):
    url = "mongodb://"+ip+":"+port
    client = pymongo.MongoClient(url)
    print("client:",client)
    return client

"""创建或连接数据库"""
def db_database(client,dbname):
    db = client[dbname]
    # dblist = client.database_names()  ## 获取数据库列表
    dblist = client.list_database_names() ## 获取数据库列表
    print("dblist:",dblist)
    if dbname not in dblist:  # 判断数据库是否存在
        print("The database has been created!")
    return db

"""创建或连接集合"""
def db_collect(db,colname):
    collect = db[colname]
    # collist = db.collection_names()  ## 获取数据库中的所有集合
    collist = db.list_collection_names()  ## 获取数据库中的所有集合
    print("collist:",collist)
    if colname not in collist:  # 判断集合是否存在
        print("The collect has been created!")
    return collect

"""测试代码"""
if __name__ == "__main__":
    print(".....start.....")
    client = db_client()    ## 连接对象
    db = db_database(client,"dbtest") ## 数据库
    collect = db_collect(db,"coltest")   ## 集合
    mydict = {"name": "RUNOOB", "alexa": "10000", "url": "https://www.runoob.com"}
    x = collect.insert_one(mydict) ## 插入单条数据
    print(x.inserted_id)
    print("......end......")

运行结果

client: MongoClient(host=['127.0.0.1:27017'], document_class=dict, tz_aware=False, connect=True)
dblist: ['admin', 'config', 'dbtest', 'local']
collist: ['coltest']

2、命令行查看结果

查看新建的数据库、集合和插入的数据

show dbs
use dbtest
show collections
db.coltest.find()

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐