构建一个类似Twitter的社交应用,包含用户、帖子、评论、点赞、关注等功能。
// 用户集合
db.users.insertOne({
_id: "user123",
username: "zhangsan",
email: "zhangsan@example.com",
password: "hashed_password",
profile: {
avatar: "avatar.jpg",
bio: "热爱技术的开发者",
location: "北京"
},
stats: {
followers: 150,
following: 80,
posts: 45
},
createdAt: new Date()
})
// 帖子集合
db.posts.insertOne({
_id: ObjectId("..."),
userId: "user123",
content: "学习MongoDB真有趣!",
images: ["image1.jpg", "image2.jpg"],
hashtags: ["MongoDB", "数据库"],
stats: {
likes: 25,
comments: 8,
shares: 3
},
createdAt: new Date()
})
// 关注关系集合
db.follows.insertOne({
followerId: "user123",
followingId: "user456",
createdAt: new Date()
})
// 点赞集合
db.likes.insertOne({
userId: "user123",
postId: ObjectId("..."),
createdAt: new Date()
})
// 评论集合
db.comments.insertOne({
_id: ObjectId("..."),
postId: ObjectId("..."),
userId: "user123",
content: "说得对!",
createdAt: new Date()
})
// 1. 发布帖子
function createPost(userId, content, images, hashtags) {
const post = db.posts.insertOne({
userId: userId,
content: content,
images: images || [],
hashtags: hashtags || [],
stats: { likes: 0, comments: 0, shares: 0 },
createdAt: new Date()
});
// 更新用户帖子数
db.users.updateOne(
{ _id: userId },
{ $inc: { "stats.posts": 1 } }
);
return post.insertedId;
}
// 2. 获取用户时间线(关注的人的帖子)
function getTimeline(userId, page = 1, pageSize = 20) {
return db.posts.aggregate([
// 关联关注关系
{
$lookup: {
from: "follows",
localField: "userId",
foreignField: "followingId",
as: "follow"
}
},
// 只显示关注的人的帖子
{
$match: {
"follow.followerId": userId
}
},
// 关联用户信息
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user"
}
},
{ $unwind: "$user" },
// 排序和分页
{ $sort: { createdAt: -1 } },
{ $skip: (page - 1) * pageSize },
{ $limit: pageSize },
// 投影
{
$project: {
content: 1,
images: 1,
hashtags: 1,
stats: 1,
createdAt: 1,
"user.username": 1,
"user.profile.avatar": 1
}
}
]);
}
// 3. 点赞功能
function likePost(userId, postId) {
// 检查是否已点赞
const existing = db.likes.findOne({
userId: userId,
postId: postId
});
if (existing) {
return { success: false, message: "已经点赞过了" };
}
// 添加点赞记录
db.likes.insertOne({
userId: userId,
postId: postId,
createdAt: new Date()
});
// 更新帖子点赞数
db.posts.updateOne(
{ _id: postId },
{ $inc: { "stats.likes": 1 } }
);
return { success: true };
}
// 4. 关注用户
function followUser(followerId, followingId) {
// 检查是否已关注
const existing = db.follows.findOne({
followerId: followerId,
followingId: followingId
});
if (existing) {
return { success: false, message: "已经关注了" };
}
// 添加关注记录
db.follows.insertOne({
followerId: followerId,
followingId: followingId,
createdAt: new Date()
});
// 更新统计数据
db.users.updateOne(
{ _id: followerId },
{ $inc: { "stats.following": 1 } }
);
db.users.updateOne(
{ _id: followingId },
{ $inc: { "stats.followers": 1 } }
);
return { success: true };
}
// 用户集合
db.users.createIndex({ username: 1 }, { unique: true })
db.users.createIndex({ email: 1 }, { unique: true })
// 帖子集合
db.posts.createIndex({ userId: 1, createdAt: -1 })
db.posts.createIndex({ hashtags: 1 })
db.posts.createIndex({ createdAt: -1 })
// 关注集合
db.follows.createIndex({ followerId: 1, followingId: 1 }, { unique: true })
db.follows.createIndex({ followingId: 1 })
// 点赞集合
db.likes.createIndex({ userId: 1, postId: 1 }, { unique: true })
db.likes.createIndex({ postId: 1 })
// 评论集合
db.comments.createIndex({ postId: 1, createdAt: -1 })
// 文章集合
db.articles.insertOne({
_id: ObjectId("..."),
title: "MongoDB最佳实践",
slug: "mongodb-best-practices",
content: "文章内容...",
excerpt: "文章摘要",
author: {
id: "user123",
name: "张三",
avatar: "avatar.jpg"
},
category: "技术",
tags: ["MongoDB", "数据库", "NoSQL"],
status: "published", // draft, published, archived
featured: true,
seo: {
metaTitle: "MongoDB最佳实践指南",
metaDescription: "深入了解MongoDB的最佳实践",
keywords: ["MongoDB", "最佳实践"]
},
stats: {
views: 1500,
likes: 89,
comments: 23
},
publishedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date()
})
// 分类集合
db.categories.insertOne({
_id: "tech",
name: "技术",
slug: "technology",
description: "技术相关文章",
parent: null, // 父分类ID
order: 1
})
// 评论集合(支持嵌套)
db.comments.insertOne({
_id: ObjectId("..."),
articleId: ObjectId("..."),
userId: "user123",
userName: "张三",
content: "写得很好!",
parentId: null, // 父评论ID(回复)
status: "approved", // pending, approved, spam
createdAt: new Date()
})
// 使用桶模式存储传感器数据
db.sensor_data.insertOne({
sensorId: "sensor001",
location: "北京-机房A",
date: ISODate("2026-02-03T10:00:00Z"),
measurements: [
{
timestamp: ISODate("2026-02-03T10:00:00Z"),
temperature: 25.5,
humidity: 60,
pressure: 1013
},
{
timestamp: ISODate("2026-02-03T10:01:00Z"),
temperature: 25.6,
humidity: 61,
pressure: 1013
}
// ... 每小时3600条数据
],
stats: {
count: 3600,
avgTemp: 25.5,
minTemp: 24.8,
maxTemp: 26.2,
avgHumidity: 60.5
}
})
// 索引
db.sensor_data.createIndex({ sensorId: 1, date: -1 })
db.sensor_data.createIndex({ location: 1, date: -1 })
// TTL索引:自动删除90天前的数据
db.sensor_data.createIndex(
{ date: 1 },
{ expireAfterSeconds: 7776000 }
)
// 查询最近24小时的数据
db.sensor_data.aggregate([
{
$match: {
sensorId: "sensor001",
date: {
$gte: new Date(Date.now() - 24*60*60*1000)
}
}
},
{ $unwind: "$measurements" },
{
$group: {
_id: null,
avgTemp: { $avg: "$measurements.temperature" },
maxTemp: { $max: "$measurements.temperature" },
minTemp: { $min: "$measurements.temperature" }
}
}
])
// 商品集合
db.products.insertOne({
_id: "prod123",
name: "笔记本电脑",
description: "高性能笔记本",
category: "电子产品",
price: 5999,
originalPrice: 6999,
stock: 50,
images: ["img1.jpg", "img2.jpg"],
attributes: [
{ key: "品牌", value: "联想" },
{ key: "CPU", value: "Intel i7" },
{ key: "内存", value: "16GB" }
],
rating: {
average: 4.5,
count: 128
},
sales: 256,
status: "active"
})
// 订单集合
db.orders.insertOne({
_id: "order123",
userId: "user123",
items: [
{
productId: "prod123",
productName: "笔记本电脑",
price: 5999,
quantity: 1,
subtotal: 5999
}
],
shipping: {
name: "张三",
phone: "13800138000",
address: "北京市朝阳区xxx",
method: "快递",
fee: 0
},
payment: {
method: "支付宝",
transactionId: "txn123",
paidAt: new Date()
},
total: 5999,
status: "paid", // pending, paid, shipped, completed, cancelled
createdAt: new Date(),
updatedAt: new Date()
})
// 购物车集合
db.carts.insertOne({
userId: "user123",
items: [
{
productId: "prod123",
quantity: 1,
addedAt: new Date()
}
],
updatedAt: new Date()
})
// 1. 备份数据库
mongodump --db mydb --out /backup/
// 2. 恢复数据库
mongorestore --db mydb /backup/mydb/
// 3. 导出集合
mongoexport --db mydb --collection users --out users.json
// 4. 导入集合
mongoimport --db mydb --collection users --file users.json
// 5. 监控副本集
rs.status()
// 6. 查看慢查询
db.system.profile.find().sort({ millis: -1 }).limit(10)
// 7. 创建用户
db.createUser({
user: "appuser",
pwd: "password",
roles: [{ role: "readWrite", db: "mydb" }]
})
你已经掌握了从基础到高级的MongoDB知识。继续实践,构建更多项目,加深理解。记住:实践是最好的老师!
选择一个实战项目,完整实现以下功能: