db.createCollection(<name>, <options>) method is used by MongoDB to
create collection.
- <name> parameter is string type; here we put the name of the collection.
- <Options> parameter is a document that specifies options about memory size and indexing etc. The options parameter is optional, so you need to specify the only the <name> of the collection. Following is the list of options you can use:
Field
|
Type
|
Description
|
capped
|
Boolean
|
The 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 the size
parameter also.
|
autoIndexID
|
Boolean
|
If true, automatically create an index on the _id field.s Default
|
size
|
number
|
If capped is true it specifies a maximum size in bytes for a capped
collection, and then you need to specify this field also.
|
max
|
number
|
This allows the maximum number of documents allowed in the capped
collection.
|
While inserting the document, MongoDB first checks the size
field of capped collection, then it checks the max field.
Example:
Following I am trying to write the basic syntax for
createCollection() method.
>use test
switched to db test
>db.createCollection("mongocollection")
{ "ok" : 1 }
>
|
You can check the created collection by using the command
show collections
>show collections
mongocollection
system.indexes
|
Following example shows the syntax of createCollection()
method with few important options:
>db.createCollection("mongocollection ", { capped :
true, autoIndexID : true, size : 6142800, max : 10000 } )
{ "ok" : 1 }
>
|
In MongoDB, you don't need to create collection. MongoDB creates
collection automatically, when you insert some document.
>db.Codefari.insert({"name" :
"Codefari"})
>show collections
mongocollection
system.indexes
codefari
>
|