MongoDB 教程
本章節(jié)我們?yōu)榇蠹医榻B如何使用 MongoDB 來創(chuàng)建集合。
MongoDB 中使用 createCollection() 方法來創(chuàng)建集合。
語法格式:
db.createCollection(name, options)
參數(shù)說明:
options 可以是如下參數(shù):
字段 | 類型 | 描述 |
---|---|---|
capped | 布爾 | (可選)如果為 true,則創(chuàng)建固定集合。固定集合是指有著固定大小的集合,當(dāng)達到最大值時,它會自動覆蓋最早的文檔。 當(dāng)該值為 true 時,必須指定 size 參數(shù)。 |
autoIndexId | 布爾 | 3.2 之后不再支持該參數(shù)。(可選)如為 true,自動在 _id 字段創(chuàng)建索引。默認(rèn)為 false。 |
size | 數(shù)值 | (可選)為固定集合指定一個最大值,以千字節(jié)計(KB)。 如果 capped 為 true,也需要指定該字段。 |
max | 數(shù)值 | (可選)指定固定集合中包含文檔的最大數(shù)量。 |
在插入文檔時,MongoDB 首先檢查固定集合的 size 字段,然后檢查 max 字段。
在 test 數(shù)據(jù)庫中創(chuàng)建 json 集合:
> use test switched to db test > db.createCollection("json") { "ok" : 1 } >
如果要查看已有集合,可以使用 show collections 或 show tables 命令:
> show collections json system.indexes
下面是帶有幾個關(guān)鍵參數(shù)的 createCollection() 的用法:
創(chuàng)建固定集合 mycol,整個集合空間大小 6142800 KB, 文檔最大個數(shù)為 10000 個。
> db.createCollection("mycol", { capped : true, autoIndexId : true, size : 6142800, max : 10000 } ) { "ok" : 1 } >
在 MongoDB 中,你不需要創(chuàng)建集合。當(dāng)你插入一些文檔時,MongoDB 會自動創(chuàng)建集合。
> db.mycol2.insert({"name" : "小白教程"}) > show collections mycol2 ...