Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

Create Collection in MongoDB

$
0
0

db.createCollection(name, options) is used by MongoDB to create collection.
Where name is name of collection to be created and Options is a document which is use to specify
 Name parameter is string type; here we put the name of collection.
Options parameter is document which Specify options about memory size and indexing etc. Options parameter is optional, so you need to specify only name of the collection. Following is the list of options you can use:


Field

Type

Description

capped
Boolean
 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
If true, automatically create index on _id field.s Default

size
number
If capped is true it’s specify 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 size field of capped collection, then it checks max field.
Example:
Following I am trying to write 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


Viewing all articles
Browse latest Browse all 265

Trending Articles