Mongodb 简明教程

MongoDB - Create Collection

在本章中,我们将介绍如何使用 MongoDB 创建集合。

In this chapter, we will see how to create a collection using MongoDB.

The createCollection() Method

MongoDB db.createCollection(name, options) 用于创建集合。

MongoDB db.createCollection(name, options) is used to create collection.

Syntax

createCollection() 命令的基本语法如下:

Basic syntax of createCollection() command is as follows −

db.createCollection(name, options)

在命令中, name 是要创建的集合的名称。 Options 是一个文档,用于指定集合的配置。

In the command, name is name of collection to be created. Options is a document and is used to specify configuration of collection.

Parameter

Type

Description

Name

String

Name of the collection to be created

Options

Document

(Optional) Specify options about memory size and indexing

“选项”参数是可选的,因此您只需要指定集合的名称。以下是您可以使用的选项列表:

Options parameter is optional, so you need to specify only the name of the collection. Following is the list of options you can use −

Field

Type

Description

capped

Boolean

(Optional) If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also.

autoIndexId

Boolean

(Optional) If true, automatically create index on _id field.s Default value is false.

size

number

(Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also.

max

number

(Optional) Specifies the maximum number of documents allowed in the capped collection.

在插入文档时,MongoDB 首先会检查带上限的集合的 size 域,然后检查 max 域。

While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.

Examples

createCollection() 方法基本语法(无选项):

Basic syntax of createCollection() method without options is as follows −

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

您可以使用命令 show collections 检查创建的集合。

You can check the created collection by using the command show collections.

>show collections
mycollection
system.indexes

以下示例显示 createCollection() 方法的语法,包括几个重要选项 −

The following example shows the syntax of createCollection() method with few important options −

> 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 会自动创建集合。

In MongoDB, you don’t need to create collection. MongoDB creates collection automatically, when you insert some document.

>db.tutorialspoint.insert({"name" : "tutorialspoint"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>