‹
pymongo
# uv pip install pymongo
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client["db"]
collection = db["collection"]
# 增
collection.insert_one({"key": "value"})
collection.insert_many([
{"key": "value"},
{"other_key": "other_value"}
])
# 查
one = collection.find_one({"key": "value"})
all = list(collection.find({"city": "北京"}))
# 条件查询
collection.find({"key": {"$gt": 18}}) # $gte $lte $lt $ne
# 正则查询
collection.find({"key": {"$regex": "^."}})
# 改
collection.update_one({"key": "value"}, {"$set": {"other_key": "other_value"}})
collection.update_many({"key": "value"}, {"$set": {"other_key": "other_value"}})
collection.update_one({"key": "value"}, {"$inc": {"age": 1}}) # age + 1
# 删
collection.delete_one({"key": "value"})
collection.delete_many({"key": {"$lt": 18}})
# 排序
collection.find().sort("key", -1) # -1 表示降序, 1 表示升序
# 分页
collection.find().skip(10).limit(10) # 跳过前10条再取10条
# 建索引
collection.create_index("key")
# 聚合
pipeline = [
{"$group": {"_id": "$key", "count": {"$sum": 1}}} # 1 表示遇到一条就加1
]
res = list(collection.aggregate(pipeline))