Mongodb-create-collection

提供:Dev Guides
移動先:案内検索

MongoDB-コレクションの作成

この章では、MongoDBを使用してコレクションを作成する方法を説明します。

createCollection()メソッド

MongoDB * db.createCollection(name、options)*は、コレクションの作成に使用されます。

構文

  • createCollection()*コマンドの基本的な構文は次のとおりです-
db.createCollection(name, options)

コマンドで、 name は作成するコレクションの名前です。 Options はドキュメントであり、コレクションの構成を指定するために使用されます。

Parameter Type Description
Name String Name of the collection to be created
Options Document (Optional) Specify options about memory size and indexing

optionsパラメーターはオプションであるため、コレクションの名前のみを指定する必要があります。 以下は、使用できるオプションのリストです-

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は最初に上限付きコレクションのサイズフィールドをチェックし、次に最大フィールドをチェックします。

オプションのない* createCollection()*メソッドの基本構文は次のとおりです-

>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" : 1 }
>

MongoDBでは、コレクションを作成する必要はありません。 MongoDBは、ドキュメントを挿入するとコレクションを自動的に作成します。

>db.finddevguides.insert({"name" : "finddevguides"})
>show collections
mycol
mycollection
system.indexes
finddevguides
>