MongoDB的集合操作
建立集合
語法格式
db.createCollection(name, {capped: <Boolean>, autoIndexId: <Boolean>, size: <number>, max <number>})
引數說明
- name: 要建立的集合的名稱
- options: 可選引數,指定有關記憶體大小及索引的選項
options引數說明
引數名 | 引數型別 | 引數說明 |
---|---|---|
capped | 布林 |
如果為 true,則建立固定集合
。預設為不啟用<br />固定集合是指有著固定大小的集合,當達到最大值時,它會自動覆蓋最早的文件。<br />
當該值為 true 時,必須指定size
引數。
|
autoIndexId | 布林 |
如為 true,自動在_id
欄位建立索引
。預設為 false |
size | 數值 |
為固定集合指定一個最大值 預設為沒有限制。 如果 capped 為 true,也需要指定該欄位。 |
max | 數值 | 指定固定集合中包含文件的最大數量。 |
_id
:mongodb在建立文件的時候會自動生成_id
作為主鍵,但不是自增的
在固定集合在插入文件時,MongoDB 首先檢查固定集合的 size 欄位,然後檢查 max 欄位。
用法例項
建立固定集合 myCollection,整個集合空間大小 1024000 KB, 文件最大個數為 10000個。
> use test switched to db test > db.createCollection("myCollection", {capped : true, autoIndexId : true, size : 1024000, max : 10000}) { "note" : "the autoIndexId option is deprecated and will be removed in a future release", "ok" : 1 } > show collections myCollection
"note" : "the autoIndexId option is deprecated and will be removed in a future release"。官方不贊成給_id
建立索引,以後釋出的版本會將這個移除
其實,在 MongoDB 中,你不需要建立集合。當你插入一些文件時,MongoDB 會自動建立集合。
> show collections myCollection > db.myCollection2.insert({"name":"緣來是你", "age":27}) WriteResult({ "nInserted" : 1 }) > show collections myCollection myCollection2 >
刪除集合
語法格式
db.collectionName.drop()
collectionName替換為集合名稱
返回值
如果成功刪除選定集合,則 drop() 方法返回 true,否則返回 false。
例項
> show collections myCollection myCollection2 > db.myCollection2.drop() true > show collections myCollection