如何在Python中使用PyMongo库连接MongoDB数据库?

2023年 8月 12日 47.9k 0

  • 安装PyMongo库
  • 在命令行中输入以下指令:

    pip install pymongo

    如果pip安装失败,可以使用以下指令安装:

    easy_install pymongo

  • 连接MongoDB数据库
  • 在Python程序中使用以下代码连接MongoDB数据库:

    import pymongo

    # 连接MongoDB数据库
    client = pymongo.MongoClient('mongodb://localhost:27017/')

    # 选择或创建数据库
    db = client['pidancode']

    # 选择或创建集合
    collection = db['news']

    # 插入数据
    data = {'title': 'Python爬虫', 'content': '学习Python爬虫入门'}
    collection.insert(data)

    # 查询数据
    result = collection.find_one({'title': 'Python爬虫'})
    print(result)

  • 常用操作
  • (1)插入数据

    使用collection.insert()方法插入一条数据:

    data = {'title': 'Python爬虫', 'content': '学习Python爬虫入门'}
    collection.insert(data)

    使用collection.insert_many()方法插入多条数据:

    data = [
    {'title': 'Python爬虫1', 'content': '学习Python爬虫入门'},
    {'title': 'Python爬虫2', 'content': '学习Python爬虫高级技巧'},
    {'title': 'Python爬虫3', 'content': '学习Scrapy框架'}
    ]
    collection.insert_many(data)

    (2)查询数据

    使用collection.find()方法查询数据:

    result = collection.find({'title': 'Python爬虫'})
    for data in result:
    print(data)

    若只查询一条数据,使用collection.find_one()方法:

    result = collection.find_one({'title': 'Python爬虫'})
    print(result)

    (3)修改数据

    使用collection.update_one()方法修改一条数据:

    # 修改title为'Python爬虫'的数据,将其content字段修改为'学习Python爬虫高级技巧'
    collection.update_one({'title': 'Python爬虫'}, {'$set': {'content': '学习Python爬虫高级技巧'}})

    (4)删除数据

    使用collection.delete_one()方法删除一条数据:

    # 删除title为'Python爬虫'的数据
    collection.delete_one({'title': 'Python爬虫'})

    相关文章

    Oracle如何使用授予和撤销权限的语法和示例
    Awesome Project: 探索 MatrixOrigin 云原生分布式数据库
    下载丨66页PDF,云和恩墨技术通讯(2024年7月刊)
    社区版oceanbase安装
    Oracle 导出CSV工具-sqluldr2
    ETL数据集成丨快速将MySQL数据迁移至Doris数据库

    发布评论