MongoDB 使用手冊
基本概念
資料庫
資料庫是 MongoDB 中最高層級的資料容器。每個資料庫都有自己的集合和權限設定。在 MongoDB 中可以建立多個資料庫,每個資料庫都是獨立的。
集合
集合就是一群 MongoDB 檔案,相當於關聯式資料庫中的表。集合中的檔案可以擁有不同的欄位,這使得集合非常靈活。與關聯式資料庫不同,集合不強制要求嚴格的預先定義模式。
檔案
檔案是 MongoDB 中的基本資料單元,由欄位和值對組成。檔案類似於 JSON 物件,使用 BSON(二進位 JSON)格式儲存。
BSON 是 JSON 檔案的二進位表示形式,有額外的資料類型支援。檔案大小上限為 16 MB。
連線 MongoDB
使用 mongosh 連線本機資料庫
mongosh
連線遠端資料庫
mongosh "mongodb://hostname:port"
使用連線字串和身份驗證
mongosh "mongodb://username:password@hostname:port/database?authSource=admin"
使用 URI 連線
mongosh "mongodb://localhost:27017,mongodb://localhost:27018/?replicaSet=myReplSet"
資料庫操作
查看資料庫
show dbs
切換/建立資料庫
use mydatabase
注意:使用 use 命令切換資料庫時,如果資料庫不存在,MongoDB 會建立它,但只有插入檔案後才會真正建立。
查看目前資料庫資訊
db.stats()
刪除資料庫
db.dropDatabase()
集合操作
查看集合
show collections
建立集合
db.createCollection("mycollection")
建立集合時指定選項
db.createCollection("mycollection", {
capped: true,
size: 1000000,
max: 100
})
刪除集合
db.mycollection.drop()
查看集合統計資訊
db.mycollection.stats()
插入檔案
MongoDB 提供以下方法將檔案插入到集合中:
插入單個檔案
db.users.insertOne({
name: "張三",
age: 30,
email: "[email protected]",
address: {
city: "臺北",
street: "忠孝東路"
},
hobbies: ["籃球", "游泳"]
})
插入多個檔案
db.users.insertMany([
{ name: "李四", age: 25, city: "高雄" },
{ name: "王五", age: 35, city: "臺中" },
{ name: "趙六", age: 28, city: "新竹" }
])
插入檔案(已過時但仍然可用)
db.users.insert({
name: "錢七",
age: 32
})
查看插入結果
# 查看插入的檔案 ID
db.users.insertOne({ name: "測試" })
# 回傳:{ acknowledged: true, insertedId: ObjectId("...") }
查詢檔案
查詢所有檔案
db.users.find()
相當於 SQL 中的 SELECT * FROM users
查詢單條記錄
db.users.findOne()
條件查詢
# 等於查詢
db.users.find({ age: 30 })
# 不等於查詢
db.users.find({ age: { $ne: 30 } })
# 大於查詢
db.users.find({ age: { $gt: 25 } })
# 大於等於查詢
db.users.find({ age: { $gte: 25 } })
# 小於查詢
db.users.find({ age: { $lt: 30 } })
# 小於等於查詢
db.users.find({ age: { $lte: 30 } })
# 範圍查詢
db.users.find({ age: { $gte: 20, $lte: 30 } })
邏輯運算子
# AND(預設)
db.users.find({ age: { $gte: 25 }, name: "李四" })
# OR
db.users.find({ $or: [{ age: { $gte: 30 } }, { name: "王五" }] })
# NOR(既不也不)
db.users.find({ $nor: [{ age: { $lt: 20 } }, { city: "臺北" }] })
# NOT
db.users.find({ age: { $not: { $gte: 25 } } })
陣列查詢
# 陣列包含元素
db.users.find({ hobbies: "籃球" })
# 陣列包含所有元素
db.users.find({ hobbies: { $all: ["籃球", "游泳"] } })
# 陣列長度
db.users.find({ hobbies: { $size: 2 } })
# 陣列特定位置元素
db.users.find({ "hobbies.0": "籃球" })
# 陣列元素滿足條件
db.users.find({ hobbies: { $elemMatch: { $eq: "籃球" } } })
巢狀檔案查詢
# 巢狀檔案欄位查詢
db.users.find({ "address.city": "臺北" })
# 巢狀檔案完全比對
db.users.find({ address: { city: "臺北", street: "忠孝東路" } })
投影查詢(只回傳指定欄位)
# 只回傳 name 和 email 欄位
db.users.find({ age: 30 }, { name: 1, email: 1 })
# 排除某個欄位
db.users.find({}, { age: 0 })
# 回傳所有欄位除了 _id
db.users.find({}, { _id: 0 })
排序
# 按年齡升序
db.users.find().sort({ age: 1 })
# 按年齡降序
db.users.find().sort({ age: -1 })
# 多欄位排序
db.users.find().sort({ age: -1, name: 1 })
限制和跳過
# 回傳前 5 條
db.users.find().limit(5)
# 跳過前 10 條,回傳接下來的 5 條(分頁)
db.users.find().skip(10).limit(5)
# 統計數量
db.users.countDocuments({ age: { $gte: 25 } })
# 估計集合中文檔數量(快但可能不精確)
db.users.estimatedDocumentCount()
游標操作
# 使用游標
var cursor = db.users.find()
while (cursor.hasNext()) {
printjson(cursor.next())
}
# forEach 遍歷
db.users.find().forEach(function(doc) {
print("Name: " + doc.name)
})
更新檔案
更新單個檔案
db.users.updateOne(
{ name: "張三" },
{ $set: { age: 31 } }
)
更新多個檔案
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
)
取代檔案
db.users.replaceOne(
{ name: "張三" },
{ name: "張三", age: 32, email: "[email protected]", city: "臺北" }
)
更新運算子
# $set - 設定欄位值
db.users.updateOne({ name: "李四" }, { $set: { age: 26 } })
# $unset - 移除欄位
db.users.updateOne({ name: "李四" }, { $unset: { email: "" } })
# $inc - 遞增/遞減
db.users.updateOne({ name: "李四" }, { $inc: { age: 1 } })
db.users.updateOne({ name: "李四" }, { $inc: { age: -1 } })
# $rename - 重新命名欄位
db.users.updateOne({ name: "李四" }, { $rename: { "name": "fullname" } })
# $mul - 乘
db.users.updateOne({ name: "李四" }, { $mul: { age: 2 } })
# $min - 取最小值
db.users.updateOne({ name: "李四" }, { $min: { age: 20 } })
# $max - 取最大值
db.users.updateOne({ name: "李四" }, { $max: { age: 40 } })
# $push - 新增元素到陣列
db.users.updateOne({ name: "李四" }, { $push: { hobbies: "跑步" } })
# $pull - 移除陣列中比對的元素
db.users.updateOne({ name: "李四" }, { $pull: { hobbies: "游泳" } })
# $addToSet - 新增元素到陣列(不重複)
db.users.updateOne({ name: "李四" }, { $addToSet: { hobbies: "籃球" } })
# $pop - 移除陣列第一個或最後一個元素
db.users.updateOne({ name: "李四" }, { $pop: { hobbies: 1 } })
upsert 操作
# 如果不存在則插入,存在則更新
db.users.updateOne(
{ name: "新使用者" },
{ $set: { age: 25, city: "臺北" } },
{ upsert: true }
)
刪除檔案
刪除單個檔案
db.users.deleteOne({ name: "張三" })
刪除多個檔案
db.users.deleteMany({ age: { $lt: 20 } })
刪除所有檔案
db.users.deleteMany({})
聚合管道
聚合管道是 MongoDB 最強大的功能之一,用於處理資料流,執行複雜的資料轉換和分析。
基本語法
db.collection.aggregate([
{ $stage1: { ... } },
{ $stage2: { ... } },
...
])
常用聚合階段
$match - 過濾檔案
db.users.aggregate([
{ $match: { age: { $gte: 25 } } }
])
$project - 投影
db.users.aggregate([
{ $project: { _id: 0, name: 1, age: 1 } }
])
$group - 分組
# 統計每個年齡的使用者數量
db.users.aggregate([
{ $group: { _id: "$age", count: { $sum: 1 } } }
])
# 統計平均年齡
db.users.aggregate([
{ $group: { _id: null, avgAge: { $avg: "$age" } } }
])
# 分組並收集名字
db.users.aggregate([
{ $group: { _id: "$city", users: { $push: "$name" } } }
])
$sort - 排序
db.users.aggregate([
{ $sort: { age: -1, name: 1 } }
])
$limit - 限制數量
db.users.aggregate([
{ $limit: 5 }
])
$skip - 跳過檔案
db.users.aggregate([
{ $skip: 10 },
{ $limit: 5 }
])
$unwind - 展開陣列
db.users.aggregate([
{ $unwind: "$hobbies" }
])
$lookup - 聯表查詢
# 假設有兩個集合:orders 和 products
db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "productId",
foreignField: "_id",
as: "productDetails"
}
}
])
聚合運算子
算術運算子
db.sales.aggregate([
{
$project: {
total: { $add: ["$price", "$tax"] },
discount: { $multiply: ["$price", 0.1] }
}
}
])
字串運算子
db.users.aggregate([
{
$project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
upperName: { $toUpper: "$name" }
}
}
])
日期運算子
db.users.aggregate([
{
$project: {
year: { $year: "$birthdate" },
month: { $month: "$birthdate" },
day: { $dayOfMonth: "$birthdate" }
}
}
])
完整範例
# 找到從 PDX 機場出發的直飛航班最多的前三大家航空公司
db.routes.aggregate([
{
$match: {
"src_airport": "PDX",
"stops": 0
}
},
{
$group: {
_id: "$airline.name",
count: { $sum: 1 }
}
},
{
$sort: { count: -1 }
},
{
$limit: 3
}
])
索引
索引支援在 MongoDB 中高效執行查詢。如果沒有索引,MongoDB 就必須掃描集合中的每個檔案以回傳查詢結果。
建立索引
# 單欄位索引
db.users.createIndex({ name: 1 })
# 降序索引
db.users.createIndex({ age: -1 })
# 複合索引
db.users.createIndex({ age: 1, name: 1 })
# 唯一索引
db.users.createIndex({ email: 1 }, { unique: true })
# 文字索引
db.users.createIndex({ description: "text" })
# 多鍵索引(陣列欄位)
db.users.createIndex({ hobbies: 1 })
# 地理空間索引
db.locations.createIndex({ location: "2dsphere" })
# 雜湊索引
db.users.createIndex({ _id: "hashed" })
查看索引
# 查看集合的所有索引
db.users.getIndexes()
# 查看集合的索引大小
db.users.totalIndexSize()
刪除索引
# 刪除指定索引
db.users.dropIndex("name_1")
# 刪除所有索引(保留 _id 索引)
db.users.dropIndexes()
# 刪除文字索引
db.users.dropIndex("description_text")
索引屬性
# 稀疏索引(只索引非空值)
db.users.createIndex({ email: 1 }, { sparse: true })
# 部分索引
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { email: { $exists: true } } }
)
# TTL 索引(自動過期)
db.sessions.createIndex(
{ createdAt: 1 },
{ $set: { expireAfterSeconds: 3600 } }
)
索引策略建議
- 為經常用於查詢條件的欄位建立索引
- 複合索引的欄位順序很重要:精確比對的欄位放在前面,範圍查詢的欄位放在後面
- 避免在寫入頻率高的集合上建立過多索引
- 使用 explain() 分析查詢效能
查詢分析
# 分析查詢
db.users.find({ age: 25 }).explain()
# 分析執行計畫
db.users.find({ age: { $gte: 25 } }).sort({ name: 1 }).explain("executionStats")
副本集操作
副本集是一組維護相同資料集的 MongoDB 執行個體,提供冗餘和高可用性。
初始化副本集
rs.initiate()
查看副本集狀態
rs.status()
查看副本集設定
rs.conf()
新增從節點
rs.add("hostname:27017")
新增仲裁節點
rs.addArb("hostname:27017")
移除節點
rs.remove("hostname:27017")
副本集選舉
當主節點不可用時,副本集會自動進行選舉。可以透過以下命令觸發選舉:
# 強制目前節點成為主節點(在特定情況下使用)
rs.stepDown()
讀取偏好
# 從主節點讀取(預設)
db.getMongo().setReadPref("primary")
# 從從節點讀取
db.getMongo().setReadPref("secondary")
# 從最近的節點讀取
db.getMongo().setReadPref("nearest")
分片操作
分片是 MongoDB 水準擴展的方式,將資料分佈到多個伺服器上。
啟用分片
sh.enableSharding("mydatabase")
對集合進行分片
sh.shardCollection("mydatabase.mycollection", { _id: 1 })
查看分片狀態
sh.status()
新增分片
sh.addShard("shard_replica_set/hostname:27017")
資料匯出匯入
使用 mongodump 和 mongorestore
匯出資料
# 匯出整個資料庫
mongodump --db=mydatabase --out=/backup
# 匯出指定集合
mongodump --db=mydatabase --collection=users --out=/backup
# 匯出並壓縮
mongodump --db=mydatabase --gzip --out=/backup
匯入資料
# 復原整個資料庫
mongorestore --db=mydatabase /backup/mydatabase
# 復原指定集合
mongorestore --db=mydatabase --collection=users /backup/mydatabase/users.bson
# 復原並壓縮
mongorestore --db=mydatabase --gzip /backup/mongodb
使用 mongoexport 和 mongoimport
匯出為 JSON
# 匯出為 JSON
mongoexport --db=mydatabase --collection=users --out=users.json
# 匯出為 JSON 陣列
mongoexport --db=mydatabase --collection=users --out=users.json --jsonArray
# 匯出 CSV
mongoexport --db=mydatabase --collection=users --out=users.csv --fields=name,age,email
從 JSON 匯入
# 從 JSON 匯入
mongoimport --db=mydatabase --collection=users --file=users.json
# 從 JSON 陣列匯入
mongoimport --db=mydatabase --collection=users --file=users.json --jsonArray
# 從 CSV 匯入
mongoimport --db=mydatabase --collection=users --file=users.csv --headerline
常用管理命令
查看伺服器狀態
db.serverStatus()
查看目前資料庫狀態
db.stats()
查看集合統計資訊
db.users.stats()
查看目前操作
db.currentOp()
查看慢查詢
# 查看最近的慢查詢
db.system.profile.find().sort({ ts: -1 }).limit(10)
強制關閉資料庫
# 在緊急情況下使用
db.adminCommand({ shutdown: 1 })
交易操作
MongoDB 4.0+ 支援多檔案交易。
基本交易
session = db.getMongo().startSession()
session.startTransaction({ readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } })
try {
session.getDatabase("mydb").accounts.updateOne(
{ accountId: 1 },
{ $inc: { balance: -100 } }
)
session.getDatabase("mydb").accounts.updateOne(
{ accountId: 2 },
{ $inc: { balance: 100 } }
)
session.commitTransaction()
} catch (error) {
session.abortTransaction()
throw error
} finally {
session.endSession()
}
變更串流
變更串流允許應用程式即時監聽資料變更。
# 監聽集合變更
var changeStream = db.users.watch()
while (changeStream.hasNext()) {
printjson(changeStream.next())
}
GridFS
GridFS 用於儲存超過 16MB 限制的大型檔案。
# 上傳檔案
mongofiles put myfile.txt
# 列出檔案
mongofiles list
# 下載檔案
mongofiles get myfile.txt
# 刪除檔案
mongofiles delete myfile.txt
