Python3 MongoDB

Documents, CRUD, indexes and aggregation basics for a document database.

Intermediate
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

OperatorMeaningExample
$gt / $gte / $ltComparison{"age": {"$gt": 18}}
$in / $ninMembership{"tag": {"$in": ["a"]}}
$set / $unsetSet / remove a field{"$set": {"a": 1}}
$incAtomic increment{"$inc": {"views": 1}}
$push / $pullAppend / 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.

Friends & Partners