文档
目标
通过 mongosh Shell 和 Python/PyMongo 完成 MongoDB 数据库创建、集合操作、文档 CRUD 和聚合管道。
环境准备
mongosh mongodb://localhost:27017
# 或 Docker:
docker exec -it mongo-dev mongosh
第一步:mongosh Shell 方式
// 切换到测试数据库(不存在则自动创建)
use hello_mongo
// 直接插入文档 = 隐式创建集合
db.users.insertMany([
{
name: "张三",
age: 21,
email: "zhangsan@example.com",
hobbies: ["编程", "篮球"],
address: { city: "北京", district: "海淀" }
},
{
name: "李四",
age: 22,
email: "lisi@example.com",
hobbies: ["编程", "摄影", "旅行"],
address: { city: "上海", district: "浦东" }
}
])
// 查询
db.users.find({ age: { $gte: 21 } })
db.users.findOne({ "address.city": "北京" })
// 投影(只返回部分字段)
db.users.find({}, { name: 1, email: 1, _id: 0 })
// 更新
db.users.updateOne(
{ name: "张三" },
{ $set: { age: 22 }, $push: { hobbies: "摄影" } }
)
// 条件更新
db.users.updateMany(
{ "address.city": "北京" },
{ $set: { "address.country": "中国" } }
)
// 删除
db.users.deleteOne({ name: "李四" })
第二步:聚合管道
// 统计各城市用户数
db.users.aggregate([
{ $group: { _id: "$address.city", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
// 展开数组统计最受欢迎爱好
db.users.aggregate([
{ $unwind: "$hobbies" },
{ $group: { _id: "$hobbies", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
第三步:Python PyMongo 方式
pip install pymongo
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client["hello_mongo"]
col = db["products"]
# 创建索引
col.create_index("name", unique=True)
# 插入
products = [
{"name": "机械键盘", "price": 299, "tags": ["外设", "办公"], "stock": 50},
{"name": "无线鼠标", "price": 89, "tags": ["外设", "移动"], "stock": 200},
]
col.insert_many(products)
# 查询
for p in col.find({"price": {"$lt": 300}}).sort("price", -1):
print(f"{p['name']}: ¥{p['price']} (库存:{p['stock']})")
# 聚合:各标签商品数
pipeline = [
{"$unwind": "$tags"},
{"$group": {"_id": "$tags", "count": {"$sum": 1}}}
]
for r in col.aggregate(pipeline):
print(f"标签[{r['_id']}]: {r['count']}件商品")
# 更新
col.update_one(
{"name": "机械键盘"},
{"$set": {"price": 259}, "$inc": {"stock": -1}}
)
client.close()
预期输出
# mongosh find
{
_id: ObjectId("..."),
name: '张三',
age: 22,
email: 'zhangsan@example.com',
hobbies: ['编程', '篮球', '摄影']
}
# Python
机械键盘: ¥299 (库存:50)
无线鼠标: ¥89 (库存:200)
标签[外设]: 2件商品
标签[办公]: 1件商品
标签[移动]: 1件商品