name: mongodb-skill description: MongoDB 文件資料庫管理技能。通過自然語言查詢、管理 MongoDB,支援文件查詢、聚合操作、索引管理、地理空間查詢等功能。當用戶提到 MongoDB、NoSQL、文件資料庫時使用此技能。
通過自然語言,輕鬆管理 MongoDB,利用其強大的文件操作能力!
Ubuntu/Debian:
sudo apt update
sudo apt install mongodb-clients
macOS:
brew install mongodb-community-shell
Python 客戶端(推薦):
pip install pymongo
使用 mongosh:
mongosh "mongodb://localhost:27017/your_database"
使用連線字串:
mongodb://username:password@localhost:27017/database
// 查詢年齡大於 25 的使用者
db.users.find({ age: { $gt: 25 } })
// 模糊查詢(正規表示式)
db.articles.find({ title: { $regex: /人工智慧/i } })
// 陣列欄位查詢(包含特定值)
db.products.find({ tags: "electronics" })
// 多條件查詢
db.users.find({
age: { $gte: 18, $lte: 35 },
status: "active"
})
// 指定返回欄位
db.users.find(
{ age: { $gt: 25 } },
{ name: 1, email: 1, _id: 0 }
)
// 統計每個分類的文章數量
db.articles.aggregate([
{ $group: {
_id: "$category",
count: { $sum: 1 }
}
},
{ $sort: { count: -1 } }
])
// 計算使用者的平均訂單金額
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$user_id",
total_spent: { $sum: "$amount" },
order_count: { $sum: 1 }
}
},
{ $addFields: {
avg_order: { $divide: ["$total_spent", "$order_count"] }
}
},
{ $sort: { total_spent: -1 } }
])
// 時間序列分析(按天統計)
db.orders.aggregate([
{
$group: {
_id: {
$dateToString: {
format: "%Y-%m-%d",
date: "$created_at"
}
},
total_amount: { $sum: "$amount" },
count: { $sum: 1 }
}
},
{ $sort: { _id: 1 } }
])
// 複雜聚合(多表 JOIN)
db.orders.aggregate([
{
$lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "user_info"
}
},
{ $unwind: "$user_info" },
{
$project: {
order_id: "$_id",
amount: 1,
user_name: "$user_info.name",
user_email: "$user_info.email"
}
}
])
// 更新單個文件
db.users.updateOne(
{ _id: ObjectId("123") },
{ $set: { last_login: new Date() } }
)
// 批次更新
db.users.updateMany(
{ status: "inactive" },
{ $set: { archived: true } }
)
// 新增欄位
db.users.updateMany(
{},
{ $set: { created_at: new Date() } }
)
// 陣列操作(新增元素)
db.products.updateOne(
{ _id: ObjectId("123") },
{ $push: { tags: "new_tag" } }
)
// 陣列操作(刪除元素)
db.products.updateOne(
{ _id: ObjectId("123") },
{ $pull: { tags: "old_tag" } }
)
// 巢狀文件更新
db.users.updateOne(
{ _id: ObjectId("123") },
{ $set: { "profile.address": "新地址" } }
)
// 陣列元素更新
db.orders.updateOne(
{ _id: ObjectId("123"), "items.product_id": ObjectId("456") },
{ $set: { "items.$.quantity": 10 } }
)
// 查詢陣列包含特定值
db.posts.find({ tags: "javascript" })
// 查詢陣列包含多個值中的任意一個
db.posts.find({ tags: { $in: ["javascript", "python"] } })
// 查詢陣列包含所有指定值
db.posts.find({ tags: { $all: ["javascript", "mongodb"] } })
// 查詢陣列長度
db.posts.find({ tags: { $size: 3 } })
// 查詢陣列的第 N 個元素
db.posts.find({ "tags.0": "javascript" })
// 建立地理索引
db.places.createIndex({ location: "2dsphere" })
// 查詢距離某點 5 公里內的地點
db.places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [116.4074, 39.9042] // [經度, 緯度]
},
$maxDistance: 5000 // 5 公里
}
}
})
// 計算距離
db.places.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [116.4074, 39.9042]
},
distanceField: "distance",
maxDistance: 5000,
spherical: true
}
}
])
// 查詢特定區域內的地點
db.places.find({
location: {
$geoWithin: {
$polygon: [
[116.3, 39.9],
[116.5, 39.9],
[116.5, 40.0],
[116.3, 40.0]
]
}
}
})
// 建立單欄位索引
db.users.createIndex({ email: 1 })
// 建立複合索引
db.orders.createIndex({ user_id: 1, created_at: -1 })
// 建立唯一索引
db.users.createIndex({ username: 1 }, { unique: true })
// 建立文本索引(全文搜尋)
db.articles.createIndex({ title: "text", content: "text" })
// 全文搜尋
db.articles.find(
{ $text: { $search: "人工智慧" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
// 檢視索引
db.users.getIndexes()
// 刪除索引
db.users.dropIndex("email_1")
完整備份:
mongodump --uri="mongodb://localhost:27017/your_database" \
--out=backup_$(date +%Y%m%d)
僅備份單個集合:
mongodump --uri="mongodb://localhost:27017/your_database" \
--collection=users --out=backup_users
使用查詢條件備份:
mongodump --uri="mongodb://localhost:27017/your_database" \
--query='{ "status": "active" }' --out=backup_active
恢復完整備份:
mongorestore --uri="mongodb://localhost:27017/your_database" backup_20260323
恢復單個集合:
mongorestore --uri="mongodb://localhost:27017/your_database" \
backup_20260323/your_database/users.bson
嵌入模式:
// 適合 1:N 關係,N 較小
{
_id: ObjectId("..."),
title: "文章標題",
comments: [
{ user_id: ObjectId("..."), content: "評論內容", created_at: Date }
]
}
引用模式:
// 適合 N:N 關係或 N 較大
{
_id: ObjectId("..."),
title: "文章標題",
comment_ids: [ObjectId("..."), ObjectId("...")]
}
// 使用事務處理多集合操作
session = db.getMongo().startSession()
session.startTransaction()
try {
db.users.updateOne(
{ _id: user_id },
{ $inc: { balance: -100 } },
{ session }
)
db.orders.insertOne(
{ user_id, amount: 100, created_at: new Date() },
{ session }
)
session.commitTransaction()
} catch (error) {
session.abortTransaction()
throw error
}
// 監聽集合的變更
changeStream = db.users.watch()
changeStream.on('change', (next) => {
console.log(next)
// 根據 next.operationType 處理不同事件
})
.limit()$where 查詢 - 使用 MongoDB 運算子reIndex()使用者: "統計每個使用者最近的訂單金額"
AI: "使用聚合管道查詢每個使用者的訂單統計"
db.orders.aggregate([
{ $match: { status: "completed" } },
{
$group: {
_id: "$user_id",
last_order_date: { $max: "$created_at" },
total_amount: { $sum: "$amount" },
order_count: { $sum: 1 }
}
},
{ $sort: { total_amount: -1 } }
])
使用者: "查詢距離天安門 5 公里內的餐廳"
AI: "使用地理空間索引查詢附近地點"
db.places.find({
type: "restaurant",
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [116.3974, 39.9093] // 天安門座標
},
$maxDistance: 5000
}
}
})
這個技能的最新版本可以在7w4.net小蔥技能站找到。
使用者: "給所有訂單新增一個 processed 欄位"
AI: "批次更新訂單文件"
db.orders.updateMany(
{ processed: { $exists: false } },
{ $set: { processed: false } }
)
開始使用: 告訴我你的 MongoDB 操作需求,我會幫你生成相應的查詢!🚀
這個 MongoDB 技能內容豐富,功能覆蓋全面,程式碼示例詳細,對查詢、聚合、索引等常用操作都有清晰說明,適合需要管理 MongoDB 的使用者參考。但它更像一份技術文件而非互動式助手,在引導使用者表達需求、驗證操作正確性方面較弱,且文件中存在少量錯字。使用前建議先明確自己的具體需求,再查詢對應章節。整體質量中上,功能實用但互動體驗有待提升。