motor
是一个适用于 MongoDB 的异步 Python 驱动,通常和 asyncio
一起使用,用于非阻塞的数据库操作。 motor
是异步库, pymongo
是同步库
以下是一些常见的 操作,主要使用异步方式,并对比同样的同步方式。
shellpip install motor pymongo
pythonimport motor.motor_asyncio
from pymongo import MongoClient # 同步操作示例使用的库
client = motor.motor_asyncio.AsyncIOMotorClient("mongodb://localhost:27017")
db = client["your_database"]
collection = db["your_collection"]
pythonclient = MongoClient("mongodb://localhost:27017")
db = client["your_database"]
collection = db["your_collection"]
pythonasync def insert_one():
result = await collection.insert_one({"name": "Alice", "age": 25})
print("Inserted ID:", result.inserted_id)
pythonresult = collection.insert_one({"name": "Alice", "age": 25})
print("Inserted ID:", result.inserted_id)
pythonasync def insert_many():
result = await collection.insert_many([{"name": "Bob", "age": 30}, {"name": "Charlie", "age": 35}])
print("Inserted IDs:", result.inserted_ids)
pythonresult = collection.insert_many([{"name": "Bob", "age": 30}, {"name": "Charlie", "age": 35}])
print("Inserted IDs:", result.inserted_ids)
pythonasync def find_one():
document = await collection.find_one({"name": "Alice"})
print("Found Document:", document)
pythondocument = collection.find_one({"name": "Alice"})
print("Found Document:", document)
pythonasync def find_many():
cursor = collection.find({"age": {"$gte": 25}})
async for document in cursor:
print(document)
pythonfor document in collection.find({"age": {"$gte": 25}}):
print(document)
pythonasync def update_one():
result = await collection.update_one({"name": "Alice"}, {"$set": {"age": 26}})
print("Matched count:", result.matched_count)
print("Modified count:", result.modified_count)
pythonresult = collection.update_one({"name": "Alice"}, {"$set": {"age": 26}})
print("Matched count:", result.matched_count)
print("Modified count:", result.modified_count)
pythonasync def update_many():
result = await collection.update_many({"age": {"$lt": 30}}, {"$set": {"status": "young"}})
print("Matched count:", result.matched_count)
print("Modified count:", result.modified_count)
pythonresult = collection.update_many({"age": {"$lt": 30}}, {"$set": {"status": "young"}})
print("Matched count:", result.matched_count)
print("Modified count:", result.modified_count)
pythonasync def delete_one():
result = await collection.delete_one({"name": "Alice"})
print("Deleted count:", result.deleted_count)
pythonresult = collection.delete_one({"name": "Alice"})
print("Deleted count:", result.deleted_count)
pythonasync def delete_many():
result = await collection.delete_many({"age": {"$gte": 30}})
print("Deleted count:", result.deleted_count)
pythonresult = collection.delete_many({"age": {"$gte": 30}})
print("Deleted count:", result.deleted_count)
pythonasync def aggregate():
pipeline = [{"$match": {"age": {"$gte": 25}}}, {"$group": {"_id": "$age", "count": {"$sum": 1}}}]
async for doc in collection.aggregate(pipeline):
print(doc)
pythonpipeline = [{"$match": {"age": {"$gte": 25}}}, {"$group": {"_id": "$age", "count": {"$sum": 1}}}]
for doc in collection.aggregate(pipeline):
print(doc)
pythonasync def create_index():
index_name = await collection.create_index("name")
print("Index created:", index_name)
pythonindex_name = collection.create_index("name")
print("Index created:", index_name)
MongoDB 中没有显式的 "表" 概念,集合相当于关系型数据库中的表。我们可以通过 list_collection_names()
方法检查集合是否存在。
pythonasync def collection_exists(db, collection_name):
collection_names = await db.list_collection_names()
return collection_name in collection_names
pythoncollection_names = db.list_collection_names()
exists = "your_collection" in collection_names
print("Collection exists:", exists)
可以使用 count_documents
方法来统计符合条件的文档数。若统计整个集合的数据量,条件为空 {}
即可。
pythonasync def count_documents():
total_count = await collection.count_documents({})
print("Total documents:", total_count)
pythontotal_count = collection.count_documents({})
print("Total documents:", total_count)
pythonasync def count_filtered_documents():
count = await collection.count_documents({"age": {"$gte": 25}})
print("Filtered documents:", count)
pythoncount = collection.count_documents({"age": {"$gte": 25}})
print("Filtered documents:", count)
MongoDB 支持丰富的查询条件,以下是一些常见的查询条件写法:
{"field": value}
{"field": {"$gt": value}}
{"field": {"$lt": value}}
{"field": {"$gte": min_value, "$lte": max_value}}
{"field": {"$ne": value}}
python# 异步示例
async def find_with_conditions():
# 查询 age 大于 25 且 name 为 "Alice" 的文档
async for doc in collection.find({"age": {"$gt": 25}, "name": "Alice"}):
print(doc)
{"field": {"$exists": True}}
{"field": {"$exists": False}}
python# 异步示例
async def find_with_field_existence():
async for doc in collection.find({"address": {"$exists": True}}):
print(doc)
可以使用 $regex
查询字符串字段的特定模式:
python# 异步示例
async def find_with_regex():
async for doc in collection.find({"name": {"$regex": "^A"}}):
print(doc) # 查询 name 字段以 "A" 开头的文档
$in
:匹配字段在指定的值列表内$nin
:匹配字段不在指定的值列表内python# 异步示例
async def find_with_in_nin():
async for doc in collection.find({"age": {"$in": [25, 30, 35]}}):
print(doc) # 查询 age 为 25、30 或 35 的文档
$and
:同时满足多个条件$or
:满足其中一个条件python# 异步示例
async def find_with_and_or():
async for doc in collection.find({
"$or": [
{"age": {"$gt": 25}},
{"name": "Alice"}
]
}):
print(doc) # 查询 age 大于 25 或 name 为 "Alice" 的文档
python# 异步示例,结合多种查询条件
async def complex_query():
query = {
"$and": [
{"age": {"$gte": 25, "$lt": 40}}, # 年龄在 25 到 40 之间
{"name": {"$regex": "^A"}}, # 名字以 "A" 开头
{"address": {"$exists": True}}, # 存在 address 字段
{"status": {"$in": ["active", "pending"]}} # status 为 "active" 或 "pending"
]
}
async for doc in collection.find(query):
print(doc)
本文作者:皓月归尘
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
预览: