MongoDB Skill - 靈活的文件資料庫管理

👤 ryanlee-gemini 📦 v1.0.0 ⭐ 4.4 ⬇️ 819 下載
💻 開發程式設計 免費

📖 技能介紹


name: mongodb-skill description: MongoDB 文件資料庫管理技能。通過自然語言查詢、管理 MongoDB,支援文件查詢、聚合操作、索引管理、地理空間查詢等功能。當用戶提到 MongoDB、NoSQL、文件資料庫時使用此技能。


MongoDB Skill - 靈活的文件資料庫管理

通過自然語言,輕鬆管理 MongoDB,利用其強大的文件操作能力!


🎯 功能特點

核心能力

  • 🔍 靈活查詢 - 自然語言描述,自動生成查詢語句
  • 📊 聚合分析 - 複雜的資料聚合和統計分析
  • 📑 文件操作 - 巢狀文件、陣列操作
  • 🌍 地理查詢 - 地理空間查詢和距離計算
  • 📈 索引管理 - 複合索引、文本索引、地理索引
  • 💾 備份恢復 - mongodump/mongrestore 完整方案

📋 使用場景

查詢場景

  • "查詢年齡大於 25 歲的使用者"
  • "查詢包含特定標籤的文章"
  • "按欄位分組統計"

聚合分析場景

  • "統計每個分類的文章數量"
  • "計算使用者的平均訂單金額"
  • "時間序列資料分析"

文件操作場景

  • "向用戶文件中新增一個 address 欄位"
  • "更新陣列中的元素"
  • "刪除巢狀欄位"

地理查詢場景

  • "查詢距離我 5 公里內的商家"
  • "查詢特定區域內的地點"

🔧 前置條件

1. 安裝 MongoDB 客戶端

Ubuntu/Debian:

sudo apt update
sudo apt install mongodb-clients

macOS:

brew install mongodb-community-shell

Python 客戶端(推薦):

pip install pymongo

2. 連線 MongoDB

使用 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
}

更改流(Change Streams)

// 監聽集合的變更
changeStream = db.users.watch()

changeStream.on('change', (next) => {
  console.log(next)
  // 根據 next.operationType 處理不同事件
})

⚡ 效能最佳化

查詢最佳化

  1. 建立合適的索引 - 為查詢欄位建立索引
  2. 使用投影 - 只返回需要的欄位
  3. 限制結果數量 - 使用 .limit()
  4. 避免 $where 查詢 - 使用 MongoDB 運算子

索引策略

  1. ESR 原則 - Equality, Sort, Range
  2. 複合索引順序 - 查詢條件順序應與索引一致
  3. 避免全表掃描 - 為大集合建立索引
  4. 定期索引維護 - 使用 reIndex()

🎓 示例對話

示例 1:複雜聚合查詢

使用者: "統計每個使用者最近的訂單金額"

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 } }
])

示例 2:地理查詢

使用者: "查詢距離天安門 5 公里內的餐廳"

AI: "使用地理空間索引查詢附近地點"

db.places.find({
  type: "restaurant",
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [116.3974, 39.9093]  // 天安門座標
      },
      $maxDistance: 5000
    }
  }
})

示例 3:文件更新

這個技能的最新版本可以在7w4.net小蔥技能站找到。

使用者: "給所有訂單新增一個 processed 欄位"

AI: "批次更新訂單文件"

db.orders.updateMany(
  { processed: { $exists: false } },
  { $set: { processed: false } }
)

⚠️ 注意事項

資料建模建議

  1. 嵌入 vs 引用 - 根據訪問頻率選擇
  2. 陣列大小限制 - 避免無限增長的陣列
  3. 文件大小限制 - 單文件最大 16MB
  4. 規範化設計 - 重複資料 vs 查詢效能

安全建議

  1. 啟用認證 - 配置使用者名稱密碼
  2. 網路隔離 - 不要暴露到公網
  3. 最小許可權 - 使用角色基礎訪問控制
  4. 敏感資料加密 - 儲存前加密

📚 參考資料


開始使用: 告訴我你的 MongoDB 操作需求,我會幫你生成相應的查詢!🚀

🤖 AI 評測

這個 MongoDB 技能內容豐富,功能覆蓋全面,程式碼示例詳細,對查詢、聚合、索引等常用操作都有清晰說明,適合需要管理 MongoDB 的使用者參考。但它更像一份技術文件而非互動式助手,在引導使用者表達需求、驗證操作正確性方面較弱,且文件中存在少量錯字。使用前建議先明確自己的具體需求,再查詢對應章節。整體質量中上,功能實用但互動體驗有待提升。

📊 多維度評分

適應性3.7
規範性4.2
有效性4.5
可靠性4.5
可信度4.8

📁 包含檔案 (4 個)

📄 SKILL.md 10.2 KB
📄 _meta.json 132 B
📄 package.json 1.3 KB
📄 skill-card.md 2.5 KB