Creating a Collection

In MongoDB a collection is automatically created when it is referenced in any command. For example, if you run an insert command :

db.student.insert({
  name: "Viraj"
})

Above command will create a collection named student if it doesn't exist already in the database. But we can explicitly create a collection using the createCollection() command. The syntax of createCollection method is :

db.createCollection(name, options)

In the above command, name will be the name of the collection and options is a document which can be used to specify configurations for the collection.

options parameter is optional, and you can simply create a collection by just providing a name for the collection. But if you want to configure your collection, you can use various options available to do so. Following are the available configuration options for creating a collection in MongoDB :


FieldTypeDescription
cappedboolean(Optional) To create a capped collection, where in we specify the the maximum size or document counts to prevent it from growing beyond a set maximum value.
sizenumber(Optional) To specify the maximum size in bytes for a capped collection. If a collection is capped and reaches its maximum size limit, MongoDB then removes older documents from it to make space for new.
maxnumber(Optional) This can be used to specify the maximum number of documents allowed in a capped collection.
validatordocument(Optional) Validates any document inserted or updated against provided validation rules.
validationLevelstring(Optional) This is used to define how strictly validation rules must be applied to existing documents during an update.

Available values are :

off No validation for inserts or updates.

strict This is the default value for this option. This instructs MongoDB to apply validation rules to all inserts and updates.

moderate This is used when we want to apply validation rules to inserts and updates on only the existing valid documents and not on the existing invalid documents.

validationActionstring(Optional) This can be used to set the action to be taken upon validation i.e. if any document fails the set validation then whether to show error or just warn about the violations. Default value is error.

Creating a Capped Collection

We can create a capped collection using the following command.

db.createCollection("student", { capped : true, size : 5242880, max : 5000 } )

This will create a collection named student, with maximum size of 5 megabytes and maximum of 5000 documents.


Drop a Collection

Any collection in a database in MongoDB can be dropped easily using the following command :

db.collection_name.drop()

drop() method will return true is the collection is dropped successfully, else it will return false.