MongoDB Create Collection

Creating a collection is an automatic task in MongoDB. This is a distinguished feature in MongoDB, where a collection is automatically created when when we insert some documents. However in MongoDB, we can also create a collection manually, using the command db.createCollection.

  • Type the command use DATABASE_NAME in the command prompt to create a new database or to select the already created database with the respective name.

For Example: use Hellodb

  • Type the command createCollection(name, options) in the command prompt to create a new collection manually.
  • The name parameter is used to define the name of the collection to be created and thus the passed parameter should be a string type value.
  • The option parameter is used to define the memory size and indexing of the collection and thus the passed parameter should be a document type value.
  • While the parameter name is a mandatory parameter, the parameter option is an optional parameter while sending the command createCollection(name, options).

For Example: db.createCollection(“HELLO”)

  • For automatic creation of the collection directly insert a document into a collection with the desired name using the Collection_Name.insert(Document_name) command.

For Example: db.HELLO.insert ({“name”: “welcome”})

  • Type the command show collections in the command prompt to check the created collection.
  • Type the command collection_name.find() in the command prompt to see the inserted document in a collection.

For Example: db.HELLO.find()

The Values to be passed in the option parameter of the command db.createCollection(name, options):

 Capped:

It takes a Boolean value to enable the capped collection ( a fixed size collection ), with the specified size, if the entered boolean value is true.

AutoIndexID:

It takes a Boolean value to automatically create an index on ID field, if the entered boolean value is true.

Size Number:

It takes a numerical value to specify the maximum size in bytes for an enabled capped collection.

Max Number:

It takes a numerical value to specify the maximum number of documents allowed in an enabled capped collection.