MongoDB Insert Document

MongoDB Insert Document – MongoDB provides two functions : db.collection.insertOne() and db.collection.insertMany() to insert one or multiple documents respectively.

In this MongoDB Tutorial, we shall learn to insert one or more documents to a MongoDB Collection with examples.

Insert Single Document to Collection in Database – db.collection.insertOne()

To insert a single document to customers collection in tutorialkart database, run the following commands

Switches to tutorialkart database.

The above command inserts the document to customers collection.
{ name: "Abhi", age: 34, cars: [ "BMW 320d", "Audi R8" ] }  .

Response contains id of the object inserted and the acknowledgement (TRUE if inserted successfully).

 

Insert Multiple Documents to Collection in Database – db.collection.insertMany()

To insert multiple document to customers collection in tutorialkart database, run the following commands

The above command inserts following documents

{ name: "Midhuna", age: 23, cars: [ "BMW 320d", "Audi R8" ], place:"Amaravati" }

{ name: "Akhil", age: 24, cars: [ "Audo A7", "Agera R" ], place:"New York" }

{ name: "Honey", age: 25, cars: [ "Audi R8" ] }

The response to the console,"acknowledged" : true  meaning documents are inserted successfully, and the corresponding object ids are provided ininsertedIds .