MongoDB - Collection介紹
2024-03-15
/使用MongoDB Compass在創建collection過程中會看到許多設定選項,今天就來聊聊這些選項的功能與collection的二三事
前言
公司目前使用 mongoDB 來當作主要的資料庫,我會使用 mongoDB 官方出的 MongoDB Compass 作資料管理,在創建 collection 過程中會看到許多設定選項,今天就來聊聊這些選項的功能與 collection 的二三事。
Collection
MongoDB stores data records as documents (specifically BSON documents) which are gathered together in collections. A database stores one or more collections of documents.
根據官網說明,mongoDB 可以分成三層結構,依層級關係由上而下分別為 Database > Collection > Document,可以在 CLI 介面下指令創建 collection,範例如下:
use myNewDB
db.createCollection( "myNewCollection" ,options)
在 createCollection()裡有很多選項可以設定,以下提出幾個介紹:
Capped Collections (上限集合)
可以在選項中限制 collection 使用的大小,如果到達使用的上限後,就會開始移除掉 collection 中最舊的 document 供新文件使用。若是有資料庫有使用副本集,oplog.rs collection 就有設定此上限
用法:
db.createCollection( "log", { capped: true, size: 100000 } )
- capped (optional): Boolean,設定 true 限制大小,如果為 true,必須設定 size
- size (optional): Number,設定最大 size(單位:bytes)
也可以下指令來查看是否此 collection 有上限:
db.collection.isCapped()
Use Custom Collation
可以在選項中允許使用者使用特定語言規則及其他細緻規則來作 index 排序
用法:
db.createCollection( "myColl", { collation: { locale: "zh" } } )
- locale: String,請參閱支援的語言和區域
- strength (optional): Integer
- caseLevel (optional): Boolean
- caseFirst (optional): String
- numericOrdering (optional): Boolean
- alternate (optional): String
- maxVariable (optional): String
- backwards (optional): Boolean
- normalization (optional): Boolean
Clustered Collections
除了語言,也允許使用者自訂索引 key 值來提高效能
用法:
db.createCollection('stocks',
{
clusteredIndex: {
key: { _id: 1 },
unique: true,
name: 'stocks clustered key'
}
}
);
- key: clustered index key,必須設定為{ _id: 1 }
- unique: Boolean,必須設定為 true
- name (optional): String,唯一識別聚集索引的名稱
結論
今天簡單的分享 mongoDB 創建 collection 的方法與可以設定的選項,之後有空會再紀錄其他選項的用法。