Create Collection

To insert data in MongoDB Database, first we have to create a collection ( like table) and document data in it. To do this, lets start MongoDB client in terminal.

A collection is like a table in MongoDB. In a MongoDB database, we can create n numbers of collections. Inside collections, we have documents ( rows ) to store data in key-value pair.

MongoDB Collection
MongoDB Collection

Start Mongo Shell

In order to connect to MongoDB database, we have to start MongoDB shell first.

Start MongoDB client


Show all databases

admin 0.000GB

cars 0.000GB

config 0.000GB

local 0.000GB

show dbs

Select a Database

switched to db cars

use cars

Check Database Name




insertOne method is used to insert single document in collection. insertOne was introduced in MongoDB 3.2.

    "_id": ObjectId("5eb44282ea2adece905a24b0"),
    "name": "swift",
    "type": "hatchback"

This is the final output in MongoDB Compass.

Primary Key

The ObjectId stored in "_id" is the primary key. The primary key is always unique for all documents.

It is always recommended to use natural primary keys in MongoDB. The primary key generated by MongoDB use 12 bytes of storage. Which means it can store 24 digits, 2 digits per byte. Lets try to understand primary keys pattern.

0 1 2 3 4 5 6 7 8 9 10 11
time machine pid inc

First four bytes are timestamp in seconds since EPOCH ( 1-jan-1947 00:00). Next three bytes are for machine. Next two for processid and last three bytes are increment.

var id=new ObjectId()






insertMany method introduced in 3.2 is used to insert multiple documents in collections. The argument in insertMany is an array of objects. See example

        "acknowledged" : true,
        "insertedIds" : [


The insert method is used to insert single or multiple documents in a collections . The is the most preferred method to insert data in mongoDB. The argument in insert method can be object ( single document ) or an array ( multiple documents ).

Insert Single

    WriteResult({ "nInserted" : 1 })
     {name:"scross",type:"crossover"} )

Insert Multiple

        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]