創(chuàng)建集合
語法格式
db.createCollection(name, {capped: <Boolean>, autoIndexId: <Boolean>, size: <number>, max <number>})
參數(shù)說明
- name: 要?jiǎng)?chuàng)建的集合的名稱
- options: 可選參數(shù),指定有關(guān)內(nèi)存大小及索引的選項(xiàng)
options參數(shù)說明
參數(shù)名 | 參數(shù)類型 | 參數(shù)說明 |
---|---|---|
capped | 布爾 | 如果為 true企锌,則創(chuàng)建固定集合 谎势。默認(rèn)為不啟用来颤。固定集合是指有著固定大小的集合,當(dāng)達(dá)到最大值時(shí)抚吠,它會(huì)自動(dòng)覆蓋最早的文檔。當(dāng)該值為 true 時(shí)弟胀,必須指定 size 參數(shù)楷力。
|
autoIndexId | 布爾 | 如為 true,自動(dòng)在 _id 字段創(chuàng)建索引 孵户。默認(rèn)為 false |
size | 數(shù)值 | 為固定集合指定一個(gè)最大值 默認(rèn)為沒有限制萧朝。 如果 capped 為 true,也需要指定該字段夏哭。 |
max | 數(shù)值 | 指定固定集合中包含文檔的最大數(shù)量检柬。 |
_id
:mongodb在創(chuàng)建文檔的時(shí)候會(huì)自動(dòng)生成_id
作為主鍵,但不是自增的在固定集合在插入文檔時(shí)竖配,MongoDB 首先檢查固定集合的 size 字段何址,然后檢查 max 字段里逆。
用法實(shí)例
創(chuàng)建固定集合 myCollection,整個(gè)集合空間大小 1024000 KB, 文檔最大個(gè)數(shù)為 10000個(gè)用爪。
> 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"原押。官方不推薦使用autoIndexId選項(xiàng),將來的版本中將刪除該選項(xiàng)偎血。其實(shí)在4.0版本已經(jīng)無法將autoIndexId設(shè)置為false了诸衔,不許自動(dòng)創(chuàng)建索引。
其實(shí)颇玷,在 MongoDB 中笨农,你不需要?jiǎng)?chuàng)建集合。當(dāng)你插入一些文檔時(shí)亚隙,MongoDB 會(huì)自動(dòng)創(chuàng)建集合磁餐。
> show collections
myCollection
> db.myCollection2.insert({"name":"緣來是你", "age":27})
WriteResult({ "nInserted" : 1 })
> show collections
myCollection
myCollection2
>
刪除集合
語法格式
db.collectionName.drop()
collectionName替換為集合名稱
返回值
如果成功刪除選定集合,則 drop() 方法返回 true阿弃,否則返回 false诊霹。
實(shí)例
> show collections
myCollection
myCollection2
> db.myCollection2.drop()
true
> show collections
myCollection