創建集合
語法格式
1
|
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個。
1
2
3
4
5
6
7
8
9
|
> 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 會自動創建集合。
1
2
3
4
5
6
7
8
|
> show collections myCollection > db.myCollection2. insert ({ "name" : "緣來是你" , "age" :27}) WriteResult({ "nInserted" : 1 }) > show collections myCollection myCollection2 > |
刪除集合
語法格式
1
|
db.collectionName. drop () |
collectionName替換為集合名稱
返回值
如果成功刪除選定集合,則 drop() 方法返回 true,否則返回 false。
實例
1
2
3
4
5
6
7
|
> show collections myCollection myCollection2 > db.myCollection2. drop () true > show collections myCollection |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://www.jianshu.com/p/99fcf5c1663f