MongoDB 創(chuàng)建集合

在本章中,我們將看到如何使用MongoDB創(chuàng)建集合。

createCollection()方法

db.createCollection(name, options)用于 MongoDB 創(chuàng)建集合。

語(yǔ)法

createCollection()命令的基本語(yǔ)法如下-

db.createCollection(name, options)

在命令中,name是要?jiǎng)?chuàng)建的集合的名稱。Options是文檔,用于指定集合的配置。

參數(shù)類型描述
Name字符串要?jiǎng)?chuàng)建的集合的名稱
Options文檔
(可選) 指定有關(guān)內(nèi)存大小和索引的選項(xiàng)

Options參數(shù)是可選的,因此您只需指定集合的名稱。以下是您可以使用的選項(xiàng)列表-

字段
類型描述
capped布爾型(可選)如果為true,則啟用上限集合。上限集合是一個(gè)固定大小的集合,當(dāng)其達(dá)到最大大小時(shí)會(huì)自動(dòng)覆蓋其最早的條目。

如果指定為true,還需要指定size參數(shù)。

autoIndexId布爾型(可選) 如果為true,則自動(dòng)在_id字段上創(chuàng)建索引。s默認(rèn)值為false。
size數(shù)字(可選)指定上限集合的最大大?。ㄒ宰止?jié)為單位)。如果capped為true,則還需要指定此字段。
max數(shù)字(可選)指定上限集合中允許的最大文檔數(shù)。

插入文檔時(shí),MongoDB首先檢查上限集合的size字段,然后檢查max字段。

實(shí)例

createCollection()沒(méi)有選項(xiàng)(Options)的方法的基本語(yǔ)法如下-

>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>

您可以使用命令 show collections 檢查創(chuàng)建的集合。

>show collections
mycollection
system.indexes

 以下示例顯示 createCollection()方法的語(yǔ)法,其中包含幾個(gè)重要選項(xiàng):

> db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } ){
"ok" : 0,
"errmsg" : "BSON field 'create.autoIndexID' is an unknown field.",
"code" : 40415,
"codeName" : "Location40415"
}
>

在MongoDB中,您無(wú)需創(chuàng)建集合。當(dāng)您插入某些文檔時(shí),MongoDB會(huì)自動(dòng)創(chuàng)建集合。

>db.nhooo.insert({"name" : "nhooo"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection
system.indexes
nhooo
>
丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清