Mongodb create collection and insert data

  1. Home
  2. MongoDB
  3. Insert Data

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 create collection and insert data
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

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.

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"}
])


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"}
])


Home  »  MongoDB   »   MongoDB Insert Document in A Collection Tutorial

In this MongoDB tutorial, we will look at how to insert document into a collection. Please note if you insert a record in a non-existing collection, then MongoDB will create a new collection for you by default.

MongoDB offers various methods to insert document in a database. In this tutorial we will talk about 3 of the mostly used MongoDB methods to insert records into collection.

Switching to MongoDB Database

First, we need to access the MongoDB shell and switching to MongoDB database to insert the record in a collection. Now, we will create a new Database using the use command. If the database is non-existing, then the use command will create a new database in MongoDB.

Run the command:

mongod

Access your MongoDB database, in my case `cardb` is my my database.

> use cardb
switched to db cardb
> db
cardb
> 

The MongoDB Insert() Method Example

The insert() method helps in inserting single or multiple documents in a collection in MongoDB. It takes a document or array of documents as a 1st argument, and as a second argument, we pass some settings in it as mentioned below in the syntax.

db.collectionName.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

Understand the Parameters

ParametersTypeDetails
document document or array An object or array of documents which has to be inserted into the collection.
writeConcern document It’s an optional parameter, It refers to the document expressing the write concern.
ordered boolean It’s an optional parameter. If this parameter is set to true, then it performs the ordered insert, if any how any error occurs it will stop processing the records in the collection. And if set to false then it will perform the unordered insert, and it will keep on processing the records in a collection even if an error occurs.

Visit MongoDB site to know more about insert method.

Insert Document without _id Field

In this example, we will be creating a cars collection and populating some records into it.

> db.cars.insert( { color: "red", mfg: 2019 } )
# WriteResult({ "nInserted" : 1 })

Insert Method Output:

> db.cars.find().pretty()
{
        "_id" : ObjectId("5d108b88d376ed70e7a36bb1"),
        "color" : "red",
        "mfg" : 2019
}

As you can see, In the example above we have created a cars collection and added some data into it. Since the cars collection wasn’t exist so MongoDB created a new cars collection, added the records into the document and assigned a new _id to the object.

MongoDB Insert Multiple Documents in Collection

In this example, we will insert multiple documents using the insert method. We can supply an array of document inside the db.collectionName.insert() method. MongoDB writes records in an ordered insert format, let us understand what ordered insert format is? While inserting the records in a collection if any error shows up, then MongoDB stops processing the rest of the documents in the array.

Enter command and hit enter:

db.cars.insert([ 
     { color: "red", mfg: 2019 },
     { color: "orange", mfg: 2015 },
     { color: "green", mfg: 2014 },
     { color: "black", mfg: 2015 }
])

Once you hit enter in the terminal following message will be displayed:

BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 4,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

Following data has been inserted in MongoDB collection:

> db.cars.find().pretty()
{
        "_id" : ObjectId("5d108e72d376ed70e7a36bb2"),
        "color" : "red",
        "mfg" : 2019
}
{
        "_id" : ObjectId("5d108e72d376ed70e7a36bb3"),
        "color" : "orange",
        "mfg" : 2015
}
{
        "_id" : ObjectId("5d108e72d376ed70e7a36bb4"),
        "color" : "green",
        "mfg" : 2014
}
{
        "_id" : ObjectId("5d108e72d376ed70e7a36bb5"),
        "color" : "black",
        "mfg" : 2015
}

Using insertOne() Method

In MongoDB we can use the db.collectionName.insertOne() method to insert a single record inside a collection. We are passing the non-existing collection with insertOne() method, and It’ll create also create a new collection for us.

The insertOne() Syntax

db.collectionName.insertOne(
   <document>,
   {
      writeConcern: <document>
   }
)

Introduction to insertOne() Parameter

ParametersTypeDetails
document document or array A document which needs to be inserted into the collection.
writeConcern document It’s an optional parameter, and it refers to the document expressing the write concern.

Click here to know more about insertOne() method .

db.employee.insert([ 
   { name: "John Doe", profile: "HR" },
   { name: "Anna Parker", profile: "Marketing" },
   { name: "Nick Fury", profile: "Admin" }
])

Following message will be shown on the terminal:

BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

You can check out newly cerated employee collection using MongoDB’s db.collectionName.find().pretty() method in the terminal:

> db.employee.find().pretty()
{
        "_id" : ObjectId("5d109ac2d376ed70e7a36bb9"),
        "name" : "John Doe",
        "profile" : "HR"
}
{
        "_id" : ObjectId("5d109ac2d376ed70e7a36bba"),
        "name" : "Anna Parker",
        "profile" : "Marketing"
}
{
        "_id" : ObjectId("5d109ac2d376ed70e7a36bbb"),
        "name" : "Nick Fury",
        "profile" : "Admin"
}

Using insertMany() Method to Insert Multiple Documents

In the final step of this MongoDB tutorial, we are going to use insertMany() method to insert multiple records in a collection.

Introduction to insertMany Syntax

db.collectionName.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

Understand The Parameters

ParametersTypeDetails
document document or array It takes an object or array of objects, and inserts in a collection.
writeConcern document It’s an optional parameter, and refers to the document expressing the write concern.
ordered boolean It’s an optional and boolean parameter, this parameter decides the mongod perform an ordered or unordered insertion in a collection.

To know more about db.collectionName.inserMany() method click here.

Insert Multiple Items using insertMany() Method

Let us insert multiple items in a shopingcart collection, however this collection doesn’t exist but insertMany() method will create the shopingcart collection for us.

db.shopingcart.insertMany([
      {item: "TV", qty: 120 },
      {item: "Mobile", qty: 255 },
      {item: "T-shirts", qty: 120 },
      {item: "Toys", qty: 120},
      {item: "PS4", qty: 111 }
])

If successfully inserted and created collection then below message will be shown on the terminal:

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5d10a197d376ed70e7a36bc5"),
                ObjectId("5d10a197d376ed70e7a36bc6"),
                ObjectId("5d10a197d376ed70e7a36bc7"),
                ObjectId("5d10a197d376ed70e7a36bc8")
        ]
}

Check out the `shopingcart` collection using MongoDB find() method:

> db.shopingcart.find().pretty()
{ "_id" : ObjectId("5d10a197d376ed70e7a36bc4"), "item" : "TV", "qty" : 120 }
{
        "_id" : ObjectId("5d10a197d376ed70e7a36bc5"),
        "item" : "Mobile",
        "qty" : 255
}
{
        "_id" : ObjectId("5d10a197d376ed70e7a36bc6"),
        "item" : "T-shirts",
        "qty" : 120
}
{
        "_id" : ObjectId("5d10a197d376ed70e7a36bc7"),
        "item" : "Toys",
        "qty" : 120
}
{
        "_id" : ObjectId("5d10a197d376ed70e7a36bc8"),
        "item" : "PS4",
        "qty" : 111
}

How do I create a collection in MongoDB?

MongoDB creates collections automatically when you insert some documents. For example: Insert a document named seomount into a collection named SSSIT. The operation will create the collection if the collection does not currently exist. If you want to see the inserted document, use the find() command.

Which command is used to insert data into collection in MongoDB?

The insert() Method To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.

How do I import data from one collection to another in MongoDB?

In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name.

How do I create a collection and document in MongoDB?

In MongoDB, you don't need to create collection. MongoDB creates collection automatically, when you insert some document.