MongoDB创建集合
在本章中,我们将看到如何使用MongoDB创建集合。
createCollection()方法
MongoDB db.createCollection(name, options) 用于创建集合。
语法
createCollection()的基本语法如下:
db.createCollection(name, options)
在命令中name是要创建的集合的名称。Options是文档,用于指定集合的配置。
范围 | 类型 | 描述 |
---|---|---|
Name | String | 要创建的集合的名称 |
Options | Document | (可选)指定有关内存大小和索引的选项 |
Options参数是可选的,因此你只需指定集合的名称。以下是你可以使用的选项列表:
字段 | 类型 | 描述 |
---|---|---|
capped | Boolean | (可选)如果为true,则启用上限集合。上限集合是一个固定大小的集合,当达到最大大小时,它将自动覆盖其最早的条目。如果指定true,则还需要指定size参数。 |
autoIndexId | Boolean | (可选)如果为true,则在_id字段上自动创建索引。s默认值为false。 |
size | number | (可选)指定上限集合的最大大小(以字节为单位)。如果capped为true,则还需要指定此字段。 |
max | number | (可选)指定上限集合中允许的最大文档数。 |
在插入文档时,MongoDB首先检查上限集合的size字段,然后检查max字段。
例子
createCollection()的基本语法没有options的方法如下:
>use test switched to db test >db.createCollection("mycollection") { "ok" : 1 } >
你可以使用show collections命令检查创建的集合:
>show collections mycollection system.indexes
以下示例显示了的语法createCollection()几个重要选项的方法:
> 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中,你无需创建集合。当你插入一些文档时,MongoDB会自动创建集合。
>db.newbiego.insert({"name" : "newbiego"}), WriteResult({ "nInserted" : 1 }) >show collections mycol mycollection system.indexes newbiego >