python3连接MongoDB4.4

2022-01-05 21:46:07 浏览数 (1)

目录

一、环境准备

1、python3安装

2、MongoDB4安装

二、安装驱动

1、pip在线安装pymogo驱动

2、pymogo驱动测试

三、连接脚本

1、脚本编写

2、命令行查看结果

一、环境准备

1、python3安装

windows离线安装python3.6.8环境:https://cloud.tencent.com/developer/article/1929280

2、MongoDB4安装

Linux 离线安装 python 3.6.10:https://cloud.tencent.com/developer/article/1818613

win10安装MongoDB4.4:https://cloud.tencent.com/developer/article/1929283

二、安装驱动

1、pip在线安装pymogo驱动

代码语言:javascript复制
pip install pymongo

2、pymogo驱动测试

代码语言:javascript复制
python
import pymongo

三、连接脚本

1、脚本编写

MongoDBConn.py

代码语言:javascript复制
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、命令行查看结果

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

代码语言:javascript复制
show dbs
use dbtest
show collections
db.coltest.find()

0 人点赞