使用PyMongo连接MongoDB的基本操作

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)

python 复制代码
    import pymongo # 如果是云服务的数据库 用公网IP连接
    
    
    client = pymongo.MongoClient(host='localhost', port=27017)
指定数据库与表
python 复制代码
    import pymongo
    
    
    client = pymongo.MongoClient(host='localhost', port=27017)
    collection = client['students']
插入数据

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

python 复制代码
    # 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)
相关推荐
全栈老石2 小时前
拆解低代码引擎核心:元数据驱动的"万能表"架构
数据库·低代码
AI攻城狮3 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽3 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健18 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞20 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
倔强的石头_21 小时前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain