MongoDB – Insert Document:
In MongoDB, Document is nothing but a key-value pairs.we can you the below commands to insert a document into a collection.
Syntax:
db.collection.insertOne() --> New command in version 3.2 db.collection.insertMany() --> New command in version 3.2 db.collection.insert()
db.collection.insert()
Let us insert a document in collection called “student”.
First check in which intended database you are in and try the below commands
testset:PRIMARY>db test testset:PRIMARY>db.students.insert({firstname:"Maria",city:"Banglore"}) WriteResult({ "nInserted" : 1 })
Now Check the inserted document in collection.
testset:PRIMARY>db.students.find() { "_id" : ObjectId("59245acd5273c93ad95b109b"), "firstname" : "Maria", "city" : "Banglore" } testset:PRIMARY>
If you Observe, we did not insert “_id “, when we insert any values by default mongoDB maintains or creates “_id” field and associated value
db.collection.insertOne() –> New command in version 3.2
This will insert a single document in collection.
Example:
testset:PRIMARY>db.students.insertOne( {firstname:"Maria",city:"Banglore"} )
db.collection.insertMany() –> New command in version 3.2
This will insert multiple documents in collection.
Example:
testset:PRIMARY>db.students.insertMany( {firstname:"Julie",city:"London"} {firstname:"john",city:"NewYork"} {firstname:"Venkat",city:"Banglore"} )