MongoDB 是以文件為導向的 NoSQL 資料庫,資料以 BSON (Binary JSON) 格式儲存。本文系統整理 MongoDB Shell 中集合與文件的核心 CRUD 操作,包含 createCollection、drop、insert、update、save、remove 等指令,並說明常用參數與實戰範例。
createCollection()db.createCollection(name, options)
name:集合名稱 (字串)。options:選擇性文件,可設定 capped、size、max、autoIndexId 等。| 參數 | 類型 | 說明 |
|---|---|---|
| capped | Boolean | true 為固定大小集合,資料滿時自動覆蓋最舊文件。需同時指定 size。 |
| size | Number | capped 為 true 時必填,單位 bytes。 |
| max | Number | 最大文件數量。 |
| autoIndexId | Boolean | 預設 false,true 時在 _id 自動建立索引。 |
> db.createCollection("jingdong") // 無參數
{ "ok" : 1 }
> db.createCollection("jingdong", { capped: true, autoIndexId: true, size: 6142800, max: 10000 })
{ "ok" : 1 }
提示: 實務上常直接透過insert隱性建立集合,無須顯式呼叫createCollection。
drop()db.COLLECTION.drop()
> use JD
switched to db JD
> show collections
jingdong jingdong1 system.indexes
> db.jingdong.drop()
true
> show collections
jingdong1 system.indexes
insert()db.COLLECTION_NAME.insert(document)
> userdoc1 = { "user_id": 1, "name": "cloud", "state": "active", "actor": "user", "e-mail": "test@qq.com", "VM_num": 2, "time": [{ "date": "2014-08-12", "hour": "10:53 PM" }] }
> userdoc2 = { "user_id": 2, "name": "testadmin", "state": "active", "actor": "admin", "e-mail": "test@qq.com", "VM_num": 2, "time": [{ "date": "2014-08-11", "hour": "06:34 AM" }] }
> doc = { "name": "peter", "position": "teacher" }
> use JD
> db.jingdong.insert(userdoc1)
WriteResult({ "nInserted" : 1 })
> db.jingdong.insert(userdoc2)
WriteResult({ "nInserted" : 1 })
> db.jingdong.insert(doc)
WriteResult({ "nInserted" : 1 })
update()db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA, options)
> db.jingdong.update(
{ "user_id": "02", "e-mail": "test@qq.com" },
{ $set: { "e-mail": "group@qq.com" } }
)
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
$set、$inc、$push 等)。multi: true> db.shiyanlou.update(
{ "e-mail": "test@qq.com" },
{ $set: { "e-mail": "group@qq.com" } },
{ multi: true }
)
save()db.COLLECTION_NAME.save({ _id: ObjectId(), NEW_DATA })
> db.shiyanlou.save({ "_id": ObjectId("53ea174ccb4c62646d9544f4"), "name": "Bob", "position": "teacher" })
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
_id 存在 → 替換整份文件 (相當 upsert)。_id 不存在 → 插入新文件。remove()db.COLLECTION_NAME.remove(DELETION_CRITERIA)
> db.shiyanlou.remove({ "name": "Bob" })
WriteResult({ "nRemoved": 1 })
執行後可用 find() 驗證刪除結果。
| 操作 | 指令語法 | 說明 |
|---|---|---|
| 建立集合 | db.createCollection(name, options) | 可設定 capped、size、max 等屬性 |
| 刪除集合 | db.COLLECTION.drop() | 永久移除集合與索引 |
| 插入文件 | db.COLLECTION.insert(doc) | 自動產生 _id |
| 更新文件 | db.COLLECTION.update(query, update, options) | 支援 $set, $inc, $push 等運算子 |
| 替換文件 | db.COLLECTION.save(doc) | 依 _id 判斷 upsert 或 replace |
| 刪除文件 | db.COLLECTION.remove(query) | 符合條件者全刪 (單文件用 justOne:true) |
updateOne、updateMany、deleteOne、deleteMany (MongoDB 3.2+ 新 API),語意更清晰。insertMany、bulkWrite 提升效能。change streams 稽核。