什么是PyMongo
PyMongo 是一个 Python 库,用于与 MongoDB 数据库进行交互。MongoDB 是一个基于文档的 NoSQL 数据库,提供高性能、可扩展性和灵活的架构。PyMongo 提供了一套工具,使得在 Python 程序中操作 MongoDB 变得简单和高效。
安装PyMongo
PyMongo地址:https://pypi.org/project/pymongo/
pip install pymongo
使用PyMongo
Mongodb语句学习请查看:Mongodb命令大全
连接Mongo
from pymongo import MongoClient# 连接MongoDB服务器,无账号密码
# client = MongoClient('localhost', 27017)# 连接MongoDB服务器,账号密码
uri = "mongodb://testuser:123456@localhost:27017/admin?authSource=admin"# 连接到 MongoDB
client = MongoClient(uri)# 检查连接
client.admin.command('ping')
选择数据库和集合
# 选择数据库
db = client['myDB']# 选择集合
collection = db['myTable']
插入数据
# 插入一条数据 insert_one
document = {"name": "Tom", "age": 25, "city": "New York"}
result = collection.insert_one(document)
print(result.inserted_id) # 返回插入id# 插入多条数据 insert_many
documents = [{"name": "Jerry", "age": 30, "city": "San Francisco"},{"name": "Spike", "age": 35, "city": "Los Angeles"}
]
results = collection.insert_many(documents)
print(results.inserted_ids) # 返回插入ids
查询数据
# 查询单个文档
result = collection.find_one({"name": "Tom"})
print(result)# 查询多个文档
results = collection.find({"city": "New York"})
for document in results:print(document)
更新数据
# 更新单个文档
result = collection.update_one({"name": "Tom"}, {"$set": {"age": 25}})
print(result.modified_count) # 返回更新影响行数# 更新多个文档
results = collection.update_many({"city": "New York"}, {"$set": {"city": "NYC"}})
print(results.modified_count) # 返回更新影响行数
删除数据
# 删除单个文档
result = collection.delete_one({"name": "Tom"})
print(result.deleted_count) # 返回删除影响行数# 删除多个文档
results = collection.delete_many({"city": "NYC"})
print(results.deleted_count) # 返回删除影响行数
聚合操作
# 聚合管道
pipeline = [{"$match": {"city": "San Francisco"}},{"$group": {"_id": "$city", "average_age": {"$avg": "$age"}}}
]# 执行聚合
results = collection.aggregate(pipeline)
for result in results:print(result)
索引操作
from pymongo import MongoClient, ASCENDING# 连接MongoDB服务器,账号密码
uri = "mongodb://testuser:123456@localhost:27017/admin?authSource=admin"# 连接到 MongoDB
client = MongoClient(uri)# 检查连接
client.admin.command('ping')# 选择数据库和集合
collection = client['mydb']['users']# 创建索引
collection.create_index([("name", ASCENDING)])# 列出索引
indexes = collection.list_indexes()
for index in indexes:print(index)# 删除索引
collection.drop_index([("name", ASCENDING)])# 列出索引
indexes = collection.list_indexes()
for index in indexes:print(index)