Basics & Data types in MongoDB

1. Basic commands & Data Types in MongoDB

1.1 Show Collections in your Database

First of all you don’t need to explicitly create a Collection. MongoDB creates one at first insertion in the collection

> Displays list of collections in the database
The following code shows how to show collection in MongoDB:

> show collections
system.indexes [System Collection]
testcoll [user created collection]

1.2 Create a collection in your database
The following code shows how to create a collection in MongoDB:

> db.testcoll.insert({"name":"ParthJoshi"});
WriteResult({ "nInserted" : 1 })

Here the collection is created and also first record is inserted into the document collection.The following code shows how to show collection in MongoDB:

> show collections

This collection is created at the time of insertion

You can also define a Collection formally before inserting
Without options parameter:

     "ok" : 1 
The above code does not use the optional parameter while creating a collection "mycollection"

With options parameter:

>db.createCollection("mycol",{capped : true, autoIndexID: true, size : 6142800, max : 10000 } )
    "ok" : 1 

Possible fields for optionsDocument to be passed as argument to createCollection function

Field Type Description
Boolean (Optional) If true, enables a capped collection. Capped collection is a collection 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.
autoIndexID Boolean (Optional) If true, automatically create index on _id field. Default value is false.
size number (Optional) Specifies a maximum size in bytes for a capped collection. 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.

Example of Formally creating collections:

db.createCollection( name, options )
Parameter Type Description
Name String Name of the collection to be created
Options Document (Optional) Specify options about memory size and indexing

1.3 Drop a collection


> db.<COLLECTION>.drop()


> db.mycollection.drop()

2. Introduction to Data types in MongoDB

BSON is a binary serialization format used to store documents and make remote procedure calls in MongoDB. The BSON specification is located at

2.1 Data types in MongoDB

Each data type has a corresponding number that can be used with the $type operator to query documents by BSON type

Type Number
Double 1
String 2
Object 3
Array 4
Binary data 5
Undefined 6
Object id 7
Boolean 8
Date 9
Null 10
Regular Expression 11
JavaScript 13
Symbol 14
JavaScript (with scope) 15
32-bit integer 16
Timestamp 17
64-bit integer 18
Min key 255
Max key 127