MongoDB 建立集合
MongoDB 建立集合
本章節我們為大家介紹如何使用 MongoDB 來建立集合。
MongoDB 中使用 createCollection() 方法來建立集合。
語法格式:
db.createCollection(name, options)
引數說明:
- name: 要建立的集合名稱
- options: 可選引數, 指定有關記憶體大小及索引的選項
options 可以是如下引數:
欄位 | 型別 | 描述 |
---|---|---|
capped | 布林 | (可選)如果為 true,則建立固定集合。固定集合是指有著固定大小的集合,當達到最大值時,它會自動覆蓋最早的文件。 當該值為 true 時,必須指定 size 引數。 |
autoIndexId | 布林 | 3.2 之後不再支援該引數。(可選)如為 true,自動在 _id 欄位建立索引。預設為 false。 |
size | 數值 | (可選)為固定集合指定一個最大值,即位元組數。 如果 capped 為 true,也需要指定該欄位。 |
max | 數值 | (可選)指定固定集合中包含文件的最大數量。 |
在插入文件時,MongoDB 首先檢查固定集合的 size 欄位,然後檢查 max 欄位。
例項
在 test 資料庫中建立 itread01 集合:
> use test switched to db test > db.createCollection("itread01") { "ok" : 1 } >
如果要檢視已有集合,可以使用 show collections 或 show tables 命令:
> show collections itread01 system.indexes
下面是帶有幾個關鍵引數的 createCollection() 的用法:
建立固定集合 mycol,整個集合空間大小 6142800 B, 文件最大個數為 10000 個。
> db.createCollection("mycol", { capped : true, autoIndexId : true, size : 6142800, max : 10000 } ) { "ok" : 1 } >
在 MongoDB 中,你不需要建立集合。當你插入一些文件時,MongoDB 會自動建立集合。
> db.mycol2.insert({"name" : "入門教學"}) > show collections mycol2 ...