首页 > 数据库 >【Python快速上手(三十一)】- Python MongoDB 详解

【Python快速上手(三十一)】- Python MongoDB 详解

时间:2024-05-26 17:59:38浏览次数:15  
标签:username Python MongoDB age 三十一 collection 文档 result

目录

Python快速上手(三十一)

Python MongoDB 详解

MongoDB 是一种 NoSQL 数据库,它使用文档存储数据,提供高性能、高可用性和易扩展性。Python 提供了 pymongo 库来与 MongoDB 进行交互。本文将详细讲解如何使用 Python 与 MongoDB 进行各种操作,包括连接数据库、CRUD 操作、查询、索引和聚合。

1. 安装 pymongo

在使用 MongoDB 前,需要安装 pymongo 库。可以使用以下命令安装:

pip install pymongo

2. 连接 MongoDB

2.1 基本连接
使用 MongoClient 类连接到 MongoDB 服务器:

from pymongo import MongoClient

client = MongoClient('localhost', 27017)

2.2 使用 URI 连接
可以使用 MongoDB URI 连接字符串:

client = MongoClient('mongodb://localhost:27017/')

2.3 访问数据库
连接到特定的数据库:

db = client['mydatabase']

或者:

db = client.mydatabase

2.4 认证
如果 MongoDB 需要认证,使用以下方式连接:

client = MongoClient('mongodb://username:password@localhost:27017/mydatabase')
db = client['mydatabase']

3. 创建和删除集合

3.1 创建集合
MongoDB 会在第一次插入文档时自动创建集合:

collection = db['mycollection']

3.2 删除集合
使用 drop 方法删除集合:

collection.drop()

4. CRUD 操作

4.1 插入文档
4.1.1 插入单个文档
使用 insert_one 方法插入一个文档:

document = {"name": "John", "age": 25, "city": "New York"}
collection.insert_one(document)

4.1.2 插入多个文档
使用 insert_many 方法插入多个文档:

documents = [
    {"name": "Anna", "age": 28, "city": "London"},
    {"name": "Mike", "age": 32, "city": "Chicago"}
]
collection.insert_many(documents)

4.2 查询文档
4.2.1 查询单个文档
使用 find_one 方法查询单个文档:

result = collection.find_one({"name": "John"})
print(result)

4.2.2 查询多个文档
使用 find 方法查询多个文档:

results = collection.find({"age": {"$gt": 20}})
for result in results:
    print(result)

4.3 更新文档
4.3.1 更新单个文档
使用 update_one 方法更新单个文档:

collection.update_one({"name": "John"}, {"$set": {"age": 26}})

4.3.2 更新多个文档
使用 update_many 方法更新多个文档:

collection.update_many({"age": {"$gt": 20}}, {"$set": {"city": "San Francisco"}})

4.4 删除文档
4.4.1 删除单个文档
使用 delete_one 方法删除单个文档:

collection.delete_one({"name": "John"})

4.4.2 删除多个文档
使用 delete_many 方法删除多个文档:

collection.delete_many({"age": {"$gt": 20}})

5. 查询操作

5.1 条件查询
使用查询操作符进行条件查询:

results = collection.find({"age": {"$gte": 25}})

常用查询操作符:

  • $eq:等于
  • $ne:不等于
  • $gt:大于
  • $gte:大于等于
  • $lt:小于
  • $lte:小于等于
  • $in:在指定数组内
  • $nin:不在指定数组内

5.2 逻辑操作符
使用逻辑操作符进行查询:

results = collection.find({"$or": [{"age": {"$lt": 25}}, {"city": "London"}]})

常用逻辑操作符:

  • $and:与
  • $or:或
  • $not:非
  • $nor:非或

5.3 正则表达式
使用正则表达式进行查询:

results = collection.find({"name": {"$regex": "^J"}})

5.4 字段选择
指定返回的字段:

results = collection.find({}, {"_id": 0, "name": 1, "age": 1})

5.5 排序
使用 sort 方法进行排序:

results = collection.find().sort("age", -1)

5.6 限制和跳过
使用 limit 和 skip 方法进行分页:

results = collection.find().skip(5).limit(10)

6. 索引

6.1 创建索引
使用 create_index 方法创建索引:

collection.create_index([("name", 1)])

6.2 列出索引
使用 list_indexes 方法列出索引:

for index in collection.list_indexes():
    print(index)

6.3 删除索引
使用 drop_index 方法删除索引:

collection.drop_index("name_1")

6.4 删除所有索引
使用 drop_indexes 方法删除所有索引:

collection.drop_indexes()

7. 聚合

7.1 基本聚合
使用 aggregate 方法进行聚合:

pipeline = [
    {"$match": {"age": {"$gte": 25}}},
    {"$group": {"_id": "$city", "average_age": {"$avg": "$age"}}}
]
results = collection.aggregate(pipeline)
for result in results:
    print(result)

7.2 聚合操作符
常用聚合操作符:

  • $match:过滤数据
  • $group:分组并进行计算
  • $sort:排序
  • $limit:限制结果数量
  • $skip:跳过指定数量的结果
  • $project:改变输出文档的结构
  • $unwind:拆分数组字段中的元素

7.3 聚合示例
计算每个城市的平均年龄:

pipeline = [
    {"$group": {"_id": "$city", "average_age": {"$avg": "$age"}}}
]
results = collection.aggregate(pipeline)
for result in results:
    print(result)

8. 其他操作

8.1 统计集合文档数量
使用 count_documents 方法统计文档数量:

count = collection.count_documents({"age": {"$gte": 25}})
print(count)

8.2 执行命令
使用 command 方法执行数据库命令:

result = db.command("serverStatus")
print(result)

9. 连接池和超时

9.1 设置连接池
可以设置连接池参数,例如最大连接数:

client = MongoClient('mongodb://localhost:27017/', maxPoolSize=50)

9.2 设置超时
可以设置连接超时和操作超时:

client = MongoClient('mongodb://localhost:27017/', serverSelectionTimeoutMS=5000, socketTimeoutMS=2000)

10. 实际应用案例

10.1 用户注册系统
以下示例展示了如何使用 MongoDB 实现一个简单的用户注册系统:

from pymongo import MongoClient
import datetime

client = MongoClient('mongodb://localhost:27017/')
db = client['user_database']
users = db['users']

# 注册用户
def register_user(username, password, email):
    user = {
        "username": username,
        "password": password,
        "email": email,
        "created_at": datetime.datetime.now()
    }
    users.insert_one(user)
    print(f"User {username} registered successfully")

# 查询用户
def find_user(username):
    user = users.find_one({"username": username})
    if user:
        print(f"User found: {user}")
    else:
        print("User not found")

# 更新用户密码
def update_password(username, new_password):
    result = users.update_one({"username": username}, {"$set": {"password": new_password}})
    if result.matched_count:
        print(f"Password updated for user {username}")
    else:
        print("User not found")

# 删除用户
def delete_user(username):
    result = users.delete_one({"username": username})

标签:username,Python,MongoDB,age,三十一,collection,文档,result
From: https://blog.csdn.net/qq_38641481/article/details/139183284

相关文章

  • 【Python快速上手(三十)】- 详解Python random 模块和 statistics 模块
    目录Python快速上手(三十)-详解Pythonrandom模块和statistics模块1.Pythonrandom模块1.1生成随机数1.2随机选择和打乱1.3随机分布1.4种子和状态2.Pythonstatistics模块2.1均值和中位数2.2众数2.3方差和标准差2.4协方差和相关性2.5分位数和百分位数2.6......
  • python requests 发送 form-data数据
    application/x-www-form-urlencoded与multipart/form-data的区别https://www.cnblogs.com/mlllily/p/14554907.html利用requests_toolbelt解决Howtosendform-datausingpythonrequests?pip3installrequests_toolbeltimportrequestsfromrequests_toolbelt.mult......
  • 【深度学习】使用python做h256编码的视频抽帧获取图片集
    文章目录前言一、python、深度学习、数据集的概念1.python2.深度学习3.数据集二、使用步骤1.从[visualstudio官网](https://code.visualstudio.com)下载2安装python环境2.1在visualstudio中安装python包2.2安装python依赖库3.安装opencV4.编写python代码5.视频抽帧......
  • 【找出第 K 大的异或坐标值】python
    4层循环暴力超时 classSolution:defkthLargestValue(self,matrix:List[List[int]],k:int)->int:nums=[]forainrange(len(matrix)):forbinrange(len(matrix[0])):num=0foriinrange(......
  • Python OpenCV #1 - OpenCV介绍
    一、OpenCV介绍1.1OpenCV-Python教程简介OpenCV由GaryBradsky于1999年在英特尔创立,第一个版本于2000年发布。VadimPisarevsky加入了GaryBradsky,管理英特尔的俄罗斯软件OpenCV团队。2005年,OpenCV被用于斯坦利,这辆车赢得了2005年DARPA大挑战赛。后来,在WillowGarage的支......
  • 【Python】函数详细介绍
    文章目录函数定义和调用参数类型返回值变量的作用域匿名函数(Lambda函数)递归函数函数定义和调用函数是组织好的、可重复使用的代码块,用来执行特定的任务。Python使用关键字def来定义函数。deffunction_name(parameters):"""docstring"""statement(s)......
  • Bayanay:一款基于Python开发的无线网络安全研究工具
    关于BayanayBayanay是一款基于纯Python开发的无线网络安全研究工具,在该工具的帮助下,无论你身处何地,都可以轻松地对周围地区的无线网络安全状况进行研究与分析。该工具可以通过使用HTML5的地理位置定位功能并结合Scapy获取到的SSID信息来对目标无线网络进行渗透测试与安全研......
  • Python限制输入的数范围
    在Python中,我们可以使用多种方法来限制用户输入的数值范围。1.使用while循环和try-except语句的方法以下是一个使用while循环和try-except语句的示例,该示例将要求用户输入一个在指定范围内的整数。假设我们要限制用户输入的数在1到100之间(包括1和100):defget_valid_input(min_v......
  • Python中Web开发-FastAPI框架
            大家好,在当今Web开发领域,高性能、易用性和可扩展性是开发者们追求的目标。Python作为一种流行的编程语言,在Web开发领域也有着强大的影响力。而在众多的PythonWeb框架中,FastAPI凭借其快速、现代和易用的特性,成为了开发者们的首选之一。本文将深入探讨FastAPI......
  • 设计模式 1 (Python版)
    设计模式解释:概念《设计模式:可复用面向对象软件的基础》面向对象的特性:封装,继承,多态接口:若干方法的集合限制实现接口的类必须按照接口给定的调用方式实现这些方法对高层模块隐藏了类的内部实现#接口实现的两种方法:#1.写一个父类,其他类必须继承这个方法,若子类不实现这......