Python3 MongoDB
Documents, CRUD, indexes and aggregation basics for a document database.
Key PointsMongoDB stores BSON documents; create indexes for every query shape and never store unbounded arrays.
Connect and Insert
Python
from pymongo import MongoClient
client = MongoClient("mongodb://127.0.0.1:27017", serverSelectionTimeoutMS=3000)
db = client["shop"]
users = db["users"]
result = users.insert_one({"name": "alice", "age": 30, "tags": ["vip"]})
print(result.inserted_id)
users.insert_many([
{"name": "bob", "age": 25},
{"name": "carol", "age": 35},
])Query
Python
users.find_one({"name": "alice"})
users.find({"age": {"$gte": 30}}).sort("age", -1).limit(10)
users.count_documents({"tags": "vip"})
users.update_one({"name": "alice"}, {"$set": {"age": 31}})
users.update_many({"age": {"$lt": 18}}, {"$set": {"minor": True}})
users.delete_one({"name": "bob"})Operators
| Operator | Meaning | Example |
|---|---|---|
| $gt / $gte / $lt | Comparison | {"age": {"$gt": 18}} |
| $in / $nin | Membership | {"tag": {"$in": ["a"]}} |
| $set / $unset | Set / remove a field | {"$set": {"a": 1}} |
| $inc | Atomic increment | {"$inc": {"views": 1}} |
| $push / $pull | Append / remove array item | {"$push": {"tags": "x"}} |
Indexes and Aggregation
Python
users.create_index("name", unique=True)
users.create_index([("age", 1), ("name", 1)]) # 复合索引,顺序有意义
pipeline = [
{"$match": {"age": {"$gte": 18}}},
{"$group": {"_id": "$city", "count": {"$sum": 1}, "avg": {"$avg": "$age"}}},
{"$sort": {"count": -1}},
]
for row in users.aggregate(pipeline):
print(row)MongoDB has no schema, but that does not mean no model. Decide field names and types up front, and version documents you plan to change.
连接与写入
Python
from pymongo import MongoClient
client = MongoClient("mongodb://127.0.0.1:27017", serverSelectionTimeoutMS=3000)
db = client["shop"]
users = db["users"]
result = users.insert_one({"name": "alice", "age": 30, "tags": ["vip"]})
print(result.inserted_id)
users.insert_many([
{"name": "bob", "age": 25},
{"name": "carol", "age": 35},
])查询
Python
users.find_one({"name": "alice"})
users.find({"age": {"$gte": 30}}).sort("age", -1).limit(10)
users.count_documents({"tags": "vip"})
users.update_one({"name": "alice"}, {"$set": {"age": 31}})
users.update_many({"age": {"$lt": 18}}, {"$set": {"minor": True}})
users.delete_one({"name": "bob"})常用操作符
| 操作符 | 含义 | 示例 |
|---|---|---|
| $gt / $gte / $lt | 比较 | {"age": {"$gt": 18}} |
| $in / $nin | 属于 / 不属于 | {"tag": {"$in": ["a"]}} |
| $set / $unset | 设置 / 删除字段 | {"$set": {"a": 1}} |
| $inc | 原子自增 | {"$inc": {"views": 1}} |
| $push / $pull | 数组追加 / 移除 | {"$push": {"tags": "x"}} |
索引与聚合
Python
users.create_index("name", unique=True)
users.create_index([("age", 1), ("name", 1)]) # 复合索引,顺序有意义
pipeline = [
{"$match": {"age": {"$gte": 18}}},
{"$group": {"_id": "$city", "count": {"$sum": 1}, "avg": {"$avg": "$age"}}},
{"$sort": {"count": -1}},
]
for row in users.aggregate(pipeline):
print(row)MongoDB 没有 schema,但不等于没有模型。字段名与类型要先定好,准备变更的文档要带版本号。