Friday, August 19, 2016

create Collections in MongoDB

Syntax:
Basic syntax of createCollection() command is as follows

db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection

Change Your DB to DB where you want to create collections:

> use test
switched to db test

> db
test

> show collections
>
>
> db.createCollection("TESTCOLLECTION", { capped : true, autoIndexID : true, size : 61428, max : 100 } )
{ "ok" : 1 }

> show collections
TESTCOLLECTION
mycol
tutorialspoint
>

capped    Boolean    (Optional) If true, enables a capped collection. Capped collection is a collection fixed size collecction 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 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.

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

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

> db.createCollection2("TESTCOLLECTION2")

> db.tutorialspoint.insert({"name" : "tutorialspoint"})
WriteResult({ "nInserted" : 1 })

> show collections
mycol
tutorialspoint
>

No comments:

Post a Comment