How to MongoDB- Create & Drop Collection

This guide is a walking through how to create & drop collections in MongoDB. A collection may store a number of documents. It is analogous to a table of an RDBMS. A collection may store documents those who are not same in structure. This is possible because MongoDB is a Schema-free database.

 

Create collection in MongoDB

MongoDB db.createCollection(name, options) is used to create collection.

Syntax:
     db.createCollection(name, options)

Collection names must begin with letters or an underscore. A Collection name may contain numbers. You can’t use “$” character within the name of a collection. “$” is reserved.

The name parameter is a string type, specifies the name of the collection to be created. The options parameter is optional, so you need to specify only the name of the collection. Following is the list of options.

 

FieldTypeDescription
cappedBoolean(Optional) If true, enables a capped collection. 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.
autoIndexIDBoolean(Optional) If true, automatically create index on _id field.s Default value is false.
sizenumber(Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also.
maxnumber(Optional) Specifies the maximum number of documents allowed in the capped collection.

 

Example
     >use lauyou
     switched to db lauyou
     >db.createCollection("mycollection")
     { "ok" : 1 }
     >

Check the created collection.

Collection List
     >show collections
     mycollection
     system.indexes

MongoDB creates collections automatically when you insert some documents.

Drop Collection in MongoDB

Here, we will see how to drop a collection using MongoDB. db.collection.drop() method is used to drop a collection from a database.

 

Syntax
     db.COLLECTION_NAME.drop()

The method also removes any indexes associated with the dropped collection.

 

Example
     >use lauyou  
     Switched to db lauyou 
     > show collections  
     mycollection
     system.indexes
     >db.mycollection.drop()
     True

Now check the collections in the database:

Collections List
     >show collections
     system.indexes

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

db.collection.dropIndex(index)drops or removes the specified index from a collection.

 

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...