数据库 MongoDB优点
MongoDB 的架构较少。它是一个文档数据库,它的一个集合持有不同的文档。从一个到另一个的文档的数量,内容和大小可能有差异。MongoDB 中单个对象的结构很清淅。MongoDB 中没有复杂的连接。MongoDB 提供深度查询的功能,因为它支持对文档的强大的动态查询。MongoDB 很容易扩展。它使用内部存储器来存储工作集,这是其快速访问的原因。
PyMongo 简介
PyMongo 是一个用于连接 MongoDB 数据库的 Python 驱动程序。它提供了一组简单而强大的 API,用于连接、查询和操作 MongoDB 数据库。以下是 PyMongo 中的一些主要类、方法和功能:
1. MongoClient: 这是用于连接 MongoDB 数据库的主要类。它提供了连接到 MongoDB 实例的方法。
- 方法:
MongoClient(host, port)
: 连接到指定的 MongoDB 服务器。MongoClient(uri)
: 使用 MongoDB URI 字符串连接到 MongoDB 服务器。MongoClient.with_uri(uri)
: 使用 MongoDB URI 字符串连接到 MongoDB 服务器,并支持额外的参数,如认证和复用现有连接池。MongoClient.start_session
: 开始一个新的会话,用于事务和因果一致性读取。MongoClient.end_session
: 结束一个会话。
2. Database: 表示 MongoDB 中的一个数据库。通过 MongoClient
对象的字典式访问,可以获取到一个数据库。
- 方法:
Database.collection_names()
: 获取数据库中所有集合的名称。Database.create_collection(name)
: 在数据库中创建一个新集合。Database.drop_collection(name)
: 删除数据库中的一个集合。
3. Collection: 表示 MongoDB 中的一个集合(类似于关系型数据库中的表)。通过 Database
对象的字典式访问,可以获取到一个集合。
- 方法:
Collection.insert_one(document)
: 插入一条记录。Collection.insert_manydocuments)
: 插入多条记录。Collection.find(filter)
: 根据过滤条件查询记录。Collection.delete_one(filter)
: 根据过滤条件删除一条记录。Collection.delete_many(filter)
: 根据过滤条件删除多条记录。Collection.update_one(filter, update)
: 根据过滤条件更新一条记录。Collection.update_many(filter, update)
: 根据过滤条件更新多条记录。Collection.aggregate(pipeline)
: 使用聚合管道查询数据。Collection.create_index(keys_or_list_of_keys, **kwargs)
: 在集合上创建一个索引。Collection.drop_index(name)
: 删除集合上的一个索引。Collection.drop_indexes()
: 删除集合上的所有索引。
4. GridFS: 用于处理大型文件存储的类。它允许将大型文件分割成多个小块进行存储。
- 方法:
GridFS.open_download_stream(file_id)
: 打开一个文件以供下载。GridFS.open_upload_stream(file_name, **kwargs)
: 打开一个文件以供上传。
5. 除了上述主要类之外,PyMongo 还提供了其他辅助类和功能,如 bson
模块(用于处理 BSON 数据类型,如 ObjectId、DateTime 等)和 pymongo.errors
模块(包含 PyMongo 中可能抛出的异常类型)。
这些类和方法为使用 Python 操作 MongoDB 数据库提供了丰富的功能。通过这些 API,可以轻松地实现数据的插入、查询、更新和删除等操作。
案例:
下面是一些 PyMongo 中常用功能和方法的详细讲解,以及相应的代码示例:
1. 连接到 MongoDB 数据库:
from pymongo import MongoClient
# 使用 MongoDB 的默认地址和端口(localhost:27017)
client = MongoClient()
# 使用指定的地址和端口
client = MongoClient('localhost', 27017)
# 使用 MongoDB URI 字符串连接,并提供用户名和密码
client = MongoClient('mongodb://username:password@localhost:27017/database_name')
2. 选择数据库和集合:
# 通过客户端对象获取数据库和集合
database = client['database_name']
collection = database['collection_name']
3. 插入数据:
# 插入一条记录
data = {'name': 'John', 'age': 30}
result = collection.insert_one(data)
print(f"Inserted document with _id: {result.inserted_id}")
# 插入多条记录
data_list = [
{'name': 'Alice', 'age': 28},
{'name': 'Bob', 'age': 32},
]
result = collection.insert_many(data_list)
print(f"Inserted {len(result.inserted_ids)} documents")
4. 查询数据:
# 查询所有记录
for document in collection.find():
print(document)
# 查询满足特定条件的记录
query = {'age': 30}
for document in collection.find(query):
print(document)
# 使用投影(仅返回指定字段)
projection = {'name': 1, 'age': 1, '_id': 0}
for document in collection.find(query, projection):
print(document)
5. 更新数据:
# 更新一条记录
filter_query = {'name': 'John'}
update_query = {'$set': {'age': 31}}
result = collection.update_one(filter_query, update_query)
print(f"Modified count: {result.modified_count}")
# 更新多条记录
filter_query = {'age': 30}
update_query = {'$set': {'age': 31}}
result = collection.update_many(filter_query, update_query)
print(f"Modified count: {result.modified_count}")
6. 删除数据:
# 删除一条记录
filter_query = {'name': 'John'}
result = collection.delete_one(filter_query)
print(f"Deleted count: {result.deleted_count}")
# 删除多条记录
filter_query = {'age': 30}
result = collection.delete_many(filter_query)
print(f"Deleted count: {result.deleted_count}")
7. 使用索引加速查询:
# 创建一个索引
keys = {'age': 1}
collection.create_index(keys)
# 使用索引查询数据
query = {'age': 30}
for document in collection.find(query):
print(document)
这些示例展示了如何使用 PyMongo 连接到 MongoDB 数据库,以及对数据库和集合执行基本的增删改查操作。在实际应用中,可以根据需求灵活使用这些方法。
参考资料
pymongo基础使用方法 - 秋叶红了 - 博客园
【RPA开发】pymongo 使用教程_pymongo使用_尹煜的博客-CSD…
Python MongoDB | 菜鸟教程
详解Pymongo常用查询方法总结_python_脚本之家
使用Python操作MongoDB - 知乎
Python连接MongoDB操作