MongoDB Insert Document in A Collection Tutorial

Last updated on: by Digamber
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
documentdocument or arrayAn object or array of documents which has to be inserted into the collection.
writeConcerndocumentIt’s an optional parameter, It refers to the document expressing the write concern.
orderedboolean 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
documentdocument or arrayA document which needs to be inserted into the collection.
writeConcerndocumentIt’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
documentdocument or arrayIt takes an object or array of objects, and inserts in a collection.
writeConcerndocumentIt’s an optional parameter, and refers to the document expressing the write concern.
orderedboolean 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
}

MongoDB Tutorials For Beginners

If you are new to MongoDB, then check out below MongoDB tutorials. These tutorials will help you to get started with MongoDB:

SeriesTutorial
1Install MongoDB on MacOS in 5 Minutes
2Install MongoDB on Windows
3MongoDB Create A Collection
4MongoDB Drop a Collection
5MongoDB Remove a Collection
6Uninstall MongoDB from Ubuntu

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.