MongoDB Insert Document

To insert document in the collection through multiple methods like insert(), insertOne() and insertMany(). it works like insert row into table in RDBMS.

Syntax:-


> db.collectionName.insert(document);

In RDBMS:-


insert into tableName(field1,field2...) values('Value1','Value2'..)

Example:-


db.employees.insert({
	name:"John",
	age: 35,
	department:"department A",
	salary:100000
})

if the document is inserted then show a message

WriteResult({ “nInserted” : 1 })

insertOne() method

This method is used to insert only one document in the collection.

Syntax:-


db.collectionName.insertOne(Document);

Example:-


> db.employees.insertOne({
	name:"Rom",
	age: 30,
	department:"department A",
	salary:50000
})

after insert successfully then show message

{
“acknowledged” : true,
“insertedId” : ObjectId(“5f26e7c0deec6e20ea057832”)
}

Note:- When use insertOne() method then show insert document id, it is generated automatically and it has unique value in the collection.

insertMany() method

This method is used to add multiple documents in the collection.

Syntax:-


db.collectionName.insertMany(multipleDocuments)

Example:-


> db.employees.insertMany([{
	name:"Tony",
	age: 31,
	department:"department B",
	salary:40000
},
{
	name:"Peter",
	age: 32,
	department:"department B",
	salary:30000
},
{
	name:"Andrew",
	age: 33,
	department:"department C",
	salary:20000
}
])

After insert successfully then show messages

{
“acknowledged” : true,
“insertedIds” : [
ObjectId(“5f26e9dedeec6e20ea057833”),
ObjectId(“5f26e9dedeec6e20ea057834”),
ObjectId(“5f26e9dedeec6e20ea057835”)
]
}

MongoDB Insert Document – Interview Questions

Q 1: How do you insert a single document?

Ans: Use insertOne() method.

Q 2: How do you insert multiple documents?

Ans: Use insertMany().

Q 3: What is _id field?

Ans: It is a unique identifier automatically generated by MongoDB.

Q 4: Can you manually set _id?

Ans: Yes.

Q 5: What happens if duplicate _id is inserted?

Ans: MongoDB throws an error.

Related MongoDB Insert Document Topics