MongoDB insert command

Mongodb Insert command | Complete tutorial in 2022

MongoDB is a compelling open-source, No-SQL database. You can install MongoDB on the cloud as well as on-premise servers as well. MongoDB has a rich command-line interface using which you can interact with mongodb.In this session, we will be exploring the Mongodb Insert command. So let’s get started.

Mongodb Insert command

To insert a document into MongoDB, we use the insert command.MongoDB provides the following methods to insert the data into MongoDB.

db.<COLLECTION_NAME>.insert(document)  
db.<COLLECTION_NAME>.insertOne(document)  
db.<COLLECTION_NAME>.insertMany(documents)  

Using the above methods, we can either insert a single document or multiple documents at .once into the MongoDB collection.

MongoDB insert example

mongodb insert example

In this session, we will see the example of each of the insert methods available in MongoDB.

Mongodb Insert

MongoDB insert command is used to insert single or multiple documents into the mongodb collection. The syntax of the mongodb insert command follows the below pattern.

db.<COLLECTION_NAME>.insert(document)

Before inserting the document, it is good to create a database and a collection by typing the below command.

use naiveskill;
db.createCollection('products')

You can follow this link to understand how to create a database and this link to know how to create a collection in mongodb.

Now let’s use the above command to insert a document into the mongo products collection.

db.products.insert({
"kind": "mobile",
"brand": "samsung",
"year": 2007
})
mongodb insert command

If the output displays “nInserted”: 1, it means 1 document gets successfully inserted into the mongoDB.

Let’s query the products database to determine if the document gets appropriately inserted using the find command.

db.products.find().pretty()
{ "_id" : ObjectId("613492b90baf0e08c7486d2a") }
{
	"_id" : ObjectId("613492fb0baf0e08c7486d2b"),
	"kind" : "mobile",
	"brand" : "samsung",
	"year" : 2007
}
>

You can follow this link to get familiar with all the basic mongodb commands.

We can also use the mongodb insert command to insert multiple documents into the mongoDB collection. In this case, you have to pass an array of documents to the db. <collection>.insert() method.

db.products.insert([{ 
  "kind": "laptop", 
  "brand": "apple", 
  "year": 2020 }, 
  {"kind": "headphone", 
  "brand": "sony",
  "year": 2015 }
  ])
mongodb insert command

As we can see from the above screenshot that mongodb has successfully inserted 2 documents

Let’s query the collection to verify if the data gets properly inserted

db.products.find().pretty()
{ "_id" : ObjectId("613492b90baf0e08c7486d2a") }
{
	"_id" : ObjectId("613492fb0baf0e08c7486d2b"),
	"kind" : "mobile",
	"brand" : "samsung",
	"year" : 2007
}
{
	"_id" : ObjectId("613496380baf0e08c7486d2c"),
	"kind" : "laptop",
	"brand" : "apple",
	"year" : 2020
}
{
	"_id" : ObjectId("613496380baf0e08c7486d2d"),
	"kind" : "headphone",
	"brand" : "sony",
	"year" : 2015
}

MongoDB insertOne

mongodb insert one

The functionality ofMongoDB insertOne is similar to that of MongoDB insert; instead, here, we are explicitly telling mongo that we are going to insert only a single record.

The mongodb insertOne command follows the below pattern

db.<COLLECTION_NAME>.insertOne(document)

Now let’s insert a document in the naive collection by using the insertOne command

db.naive.insertOne({
	"name": "ramesh",
	"age": 23,
	"occupation": "business"
})

The output of the above command will be

db.naive.insertOne({
... "name": "ramesh",
... "age": 23,
... "occupation": "business"
... })
{
	"acknowledged" : true,
	"insertedId" : ObjectId("6134990c0baf0e08c7486d2e")
}

“acknowledged”: true = means the document gets successfully inserted into the mongodb collection.

“insertedId”: ObjectId(“6134990c0baf0e08c7486d2e”) = means every document you will insert into the mongodb gets a unique objectId

NOTE: Here, we have not created any collection before inserting the document into the mongodb as mongodb is intelligent enough to create the collection before inserting it if the collection does not exist.

Type the below command to verify the document.

db.naive.find()
{ "_id" : ObjectId("6134990c0baf0e08c7486d2e"), "name" : "ramesh", "age" : 23, "occupation" : "business" }

MongoDB insertMany/MongoDB insert multiple documents

mongodb insert many

In mongodb, we can insert multiple documents using theinsertMany command. The mongodbinsertMany() command follows the below pattern.

db.<COLLECTION_NAME>.insertOne(document)

Now use theinsertMany() command to insert multiple documents in the naive mongo collection.

db.naive.insertMany([
  {"name": "john","age": 21,"occupation": "painter"},
  {"name": "asim","age": 29,"occupation": "engineer"},
  {"name": "gita","age": 31,"occupation": "housewife"}
  ])
db.naive.insertMany([
...   {"name": "john","age": 21,"occupation": "painter"},
...   {"name": "asim","age": 29,"occupation": "engineer"},
...   {"name": "gita","age": 31,"occupation": "housewife"}
...   ])
{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("61349d250baf0e08c7486d2f"),
		ObjectId("61349d250baf0e08c7486d30"),
		ObjectId("61349d250baf0e08c7486d31")
	]
}

Fantastic, all data gets successfully inserted into the naive collection. Let’s query the collection and find out the documents.

db.naive.find()
{ "_id" : ObjectId("6134990c0baf0e08c7486d2e"), "name" : "ramesh", "age" : 23, "occupation" : "business" }
{ "_id" : ObjectId("61349d250baf0e08c7486d2f"), "name" : "john", "age" : 21, "occupation" : "painter" }
{ "_id" : ObjectId("61349d250baf0e08c7486d30"), "name" : "asim", "age" : 29, "occupation" : "engineer" }
{ "_id" : ObjectId("61349d250baf0e08c7486d31"), "name" : "gita", "age" : 31, "occupation" : "housewife" }

Mongodb insert if does not exists

Sometimes in MongoDB, we might need to verify if the documents already exist before inserting them into the mongo collection. There are different methods to achieve this, but the easiest and most popular of them is using upsert: true flag while updating a MongoDB document.

You can check this tutorial on the mongodb update command to get a complete understanding of how the mongodb insert command works.

The mongodb update command withupsert: true follows the below pattern

db.collection.update(<query>, <update>, {upsert: true})

where

  • query: is the query to filter out the record
  • update: is the updated fields to be present in the document?
  • upsert: true: Flag is used to insert a document if the documents do not exist.

Now let’s use the update command with the upsert flag to insert a document that already exists in mongodb

type the below command to list all data present in the naive database

db.naive.find()
{ "_id" : ObjectId("6134990c0baf0e08c7486d2e"), "name" : "ramesh", "age" : 23, "occupation" : "business" }
{ "_id" : ObjectId("61349d250baf0e08c7486d2f"), "name" : "john", "age" : 21, "occupation" : "painter" }
{ "_id" : ObjectId("61349d250baf0e08c7486d30"), "name" : "asim", "age" : 29, "occupation" : "engineer" }
{ "_id" : ObjectId("61349d250baf0e08c7486d31"), "name" : "gita", "age" : 31, "occupation" : "housewife" }

Now let’s try to insert the same document where “name”: “john” and analyze the behavior

db.naive.update(
  {"name": "john" },
  {"name": "john","age": 21,"occupation": "painter"},
  {upsert:true})

output

db.naive.update(
...   {"name": "john" },
...   {"name": "john","age": 21,"occupation": "painter"},
...   {upsert:true})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

As you can see from the above output, no record was upserted because the query matches one entry. Hence no record gets not inserted.

Let’s query the naive database to find out all the records.

db.naive.find()
{ "_id" : ObjectId("6134990c0baf0e08c7486d2e"), "name" : "ramesh", "age" : 23, "occupation" : "business" }
{ "_id" : ObjectId("61349d250baf0e08c7486d2f"), "name" : "john", "age" : 21, "occupation" : "painter" }
{ "_id" : ObjectId("61349d250baf0e08c7486d30"), "name" : "asim", "age" : 29, "occupation" : "engineer" }
{ "_id" : ObjectId("61349d250baf0e08c7486d31"), "name" : "gita", "age" : 31, "occupation" : "housewife" }

As you can see from the above o/p, no record was inserted since data was already present.

MongoDB insert date

Sometimes while inserting data into the mongodb, users want the date field to be added to the document. With the new date() function, this can be achieved in mongodb

The new date() function follows the below pattern

fieldname: new Date(year,month, day, hour, minute);

if you do not specify any parameter in the Date function, it will consider the current date as the date field. Now let’s insert a document with date fields in the test collection

db.test.insert({
  "name": "ram",
  dateAdded: new Date()
  })

type the below command to fetch the document from the test collection

db.test.find()
{ "_id" : ObjectId("6134ee390baf0e08c7486d34"), "name" : "ram", "dateAdded" : ISODate("2021-09-05T16:20:09.047Z") }

Awesome, now let’s try to insert a new document with a custom date

db.test.insert({"name": "ram", dateAdded: new Date(2019, 03, 29, 13, 12)})

Query the data and find out the record which gets inserted

db.test.find()
{ "_id" : ObjectId("6134ee390baf0e08c7486d34"), "name" : "ram", "dateAdded" : ISODate("2021-09-05T16:20:09.047Z") }
{ "_id" : ObjectId("6134eebc0baf0e08c7486d35"), "name" : "ram", "dateAdded" : ISODate("2019-04-29T13:12:00Z") }

Mongodb insert python

Mongodb provides drivers in many languages using which users can interact with mongodb and perform all the operations, which we generally do using the mongo shell. One of the most popular drivers is the python driver.

Pymongo is the officially recommended driver to work with MongoDB using Python. To work with pymongo first, we need to install the pymongo driver in our mongodb servers. You can check out this link to get the complete tutorial on pymongo

A database needs to be created first before inserting a document into the mongodb. To create a database, first, create a mongo client. Once the client gets created, we can use that client to insert the document into the mongodb.

import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client['naiveskill']

Now type the below command to create a collection name mycollection

collection = db['myCollection']

Finally, type the below command to insert document a single document into the mongodb

dict= {'job': 'softare engineer' , 'Grade':7}
collection.insert_one(dict)

Insert data into MongoDB compass

Insert data into MongoDB compass

In this session, we will learn to insert data into the mongodb collection using a mongodb compass. Follow this link to download the compass in your system. Now Open the Mongodb compass application and type the below connection string to connect to mongodb.

Open the Mongodb compass and paste the below connection string to connect to mongodb.

mongodb://localhost:27017/admin
mongodb compass dashboard

Now click on create a database to create a new product database and a collection name categories.

mongodb compass create collection

Once the database gets created, it will be shown in the dashboard

mongodb compass show database

Now click on the product database to list all the collections present in the product database.

mongodb compass show collections

Now click on categories collection and add data > Insert Documents.

mongodb compass insert document

Insert 3 documents as per the below screenshot

mongodb compass insert document

Once the documents get successfully added, they will be shown below UI

mongodb compass show document

Congratulation, you are now aware of how to add a document into mongodb via compass.

Conclusion

I hope you have liked this tutorial on MongoDB insert command. This article has explored all the possible ways to insert a document into the mongodb collection.

Please do let me know in the comment box if you face any issues while following along.

More to explore?

How to create a database in mongodb

Install MongoDB using docker

MongoDB vs Mysql

Mongodb vs PostgreSQL

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top