使用PyMongo连接MongoDB的基本操作

发布于:2025-05-07 ⋅ 阅读:(54) ⋅ 点赞:(0)

MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档、数组及文档数组。在这一节中,我们就来回顾Python 3MongoDB的存储操作。

常用命令:

  1. 查询数据库: show dbs

  2. 使用数据库: use 库名

  3. 查看集合: show tables/show collections

  4. 查询表数据: db.集合名.find()

  5. 删除表: db.集合名.drop()

链接MongoDB

连接MongoDB时,我们需要使用PyMongo库里面的MongoClient。一般来说,传入MongoDBIP及端口即可,其中第一个参数为地址host,第二个参数为端口port(如果不给它传递参数,默认是27017)

    import pymongo # 如果是云服务的数据库 用公网IP连接
    
    
    client = pymongo.MongoClient(host='localhost', port=27017)

指定数据库与表
    import pymongo
    
    
    client = pymongo.MongoClient(host='localhost', port=27017)
    collection = client['students']
插入数据

对于students这个集合,新建一条学生数据,这条数据以字典形式表示:

    # pip install pymongo
    import pymongo
    
    mongo_client = pymongo.MongoClient(host='localhost', port=27017)
    collection = mongo_client['students']['stu_info']
    
    # 插入单条数据
    # student = {'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
    # result = collection.insert_one(student)
    # print(result)
    
    
    # 插入多条数据
    student_1 = {'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
    student_2 = {'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
    result = collection.insert_many([student_1, student_2])
    print(result)


网站公告

今日签到

点亮在社区的每一天
去签到