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

mongo

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

cars

db


insertOne

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

{
    "_id": ObjectId("5eb44282ea2adece905a24b0"),
    "name": "swift",
    "type": "hatchback"
}
   
db.suzuki.insertOne(
     {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.

mongo
var id=new ObjectId()

ObjectId("5eb451b9f2e0e1f61b7cfe07")

id

ISODate("2020-05-07T18:21:45Z")

id.getTimestamp()

insertMany

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" : [
                ObjectId("5eb5378791fc73f290f38251"),
                ObjectId("5eb5378791fc73f290f38252")
        ]
}
   
db.suzuki.insertMany([
     {name:"swift",type:"hatchback"},
     {name:"baleno",type:"hatchback"},
     {name:"ciaz",type:"sedan"}
])


insert

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 })
   
db.suzuki.insert(
     {name:"scross",type:"crossover"} )

Insert Multiple

    BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
   
db.suzuki.insert([
     {name:"brezza",type:"suv"},
     {name:"gypsy",type:"suv"}
])