Mongodb Create Collection

By Yashwant Chavan, Views 4179, Date 18-Oct-2016

In this tutorial we will learn how to create new collection with different options, Capped collection, collection with document validation option. Use db.createCollection(name, options) method to create new collection in the database.

tags mongodb

mongoDB Create Collection - db.createCollection(name, options)

Creates a new collection in the database. Refer following createCollection() method syntax.

db.createCollection(name, options);

name - String type parameter , The name of the collection which you want to create

options - Optional Document type parameter. Extra configuration while creating new collection. e.g. capped collection, with preallocated space, limit the number of documents etc.

options document contains the following fields

db.createCollection(<name>, { capped: <boolean>,
                              autoIndexId: <boolean>,
                              size: <number>,
                              max: <number>,
                              storageEngine: <document>,
                              validator: <document>,
                              validationLevel: <string>,
                              validationAction: <string>,
                              indexOptionDefaults: <document> } );

capped - Optional boolean parameter, To create a capped collection, specify true. If you specify true value, you must also set a maximum size in the size field.

autoIndexId - Optional boolean parameter, Specify false to disable the automatic creation of an index on the _id field

size - Optional number type parameter, Specify a maximum size in bytes for a capped collection.

max - Optional number type parameter, The maximum number of documents allowed in the capped collection.

usePowerOf2Sizes - Optional boolean type parameter, It is available only for MMAPv1 storage engine.

noPadding - Optional boolean type parameter, It is available only for MMAPv1 storage engine.

storageEngine - Optional boolean type parameter, new in version 3.0. Available for the WiredTiger storage engine only.

validator - Optional document type parameter, new in version 3.2. Allows users to specify validation rules on documents or expressions for the collection.

validationLevel - Optional string type parameter, new in version 3.2. Determines how strictly MongoDB applies the validation rules to existing documents during an update.

validationAction - Optional string type parameter, new in version 3.2. Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted.

indexOptionDefaults - Optional string type parameter, new in version 3.2. Allows users to specify a default configuration for indexes when creating a collection.

Create Basic collection

In this example we have created persons collection without options parameter.

> use technicalkeeda
switched to db technicalkeeda

> db.createCollection("persons");
{ "ok" : 1 }

> show collections

Create Capped collection

Capped collections have maximum size or document counts that prevent them from growing beyond specified threshold limit. MongoDB removes older documents if a collection reaches the maximum size.

Below command creates a logs collection with a maximum size of 5 megabytes and a maximum of 5000 documents.

> db.createCollection("logs", { capped : true, size : 5242880, max : 5000 } )
{ "ok" : 1 }

> show collections

Create collection without createCollection() method

In mongoDB, If the collection does not exist, and you use insert() method directly then insert() method will create the new collection in the database. Refer below example we have not created animals collection.

> show collections

> db.animals.insert( { _id : 1, animal: "Cow"} );
WriteResult({ "nInserted" : 1 })

> show collections

Create Collection with Document Validation Option

Specify document validation rules while creating a new collection using db.createCollection() with the validator option. In below example we have created profiles collection with validation rules.

Validation rules are applied on name and maritalStatus fields. MongoDB will display the error message and reject documents that violate the validation rules.

> db.createCollection( "profiles",
  validator: { $or:
    { name: { $type: "string" } },
    { maritalStatus: { $in: [ "Unmarried", "Divorced" , "Widow","Widower" ] } }
   validationAction: "error",
   validationLevel: "strict"
{ "ok" : 1 }

> db.profiles.insert( { name: "Yashwant Chavan", maritalStatus: "active" } )
        "nInserted" : 0,
        "writeError" : {
                "code" : 121,
                "errmsg" : "Document failed validation"
Yashwant Chavan

Yashwant Chavan

Hi there! I am founder of and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: