MongoDB Insert Document

Insert document is used to add a document to a collection.

Insert Document Syntax :

The syntax of the Insert Document is −

 
\\Insert Document in MongoDB 
db.collection_name.insert()


Insert Document Example :

The Example of the Insert Document is −

Now we are inserting a document into the collection named mydb.

\\Example of Inserting a document in MongoDB
db.mydbs.insert(  
{  
name: "Rahul",  
age: 25,
email: "admin@letsfindcourse.com",
course: [ { name: "MongoDB", duration: 7 }, { name: "Java", duration: 30 } ]
}  
)
---------------------
---------------------
\\You should see a successful message like this:
WriteResult({ "nInserted" : 1 })


Inserting Multiple Document Example :

The Example of the Inserting Multiple Document is −

So first we have to define an array of documents and after that we will use the insert() method on the array variable.

mydbs:- Collection name
This command will insert data into the "mydbs" collection, if the collection does not exist, it will create the collection and insert these documents.

\\Example of Inserting Multiple document in MongoDB
var lfc =
[
{
"StudentId" : 105,
"StudentName" : "John",
"age": 28
},
{
"StudentId" : 110,
"StudentName" : "Smith",
"age": 35
},
{
"StudentId" : 143,
"StudentName" : "Randy",
"age": 47
},
];
db.mydbs.insert(lfc);
---------------------
---------------------
\\You would see this output:
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})






Visit :


Discussion



* You must be logged in to add comment.