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 command
use tutorialkart
This command, switches to tutorialkart database.
Now, run the following command to insert the below specified document to customers collection.
{ name: “Abhi”, age: 34, cars: [ “BMW 320d”, “Audi R8” ] } .
db.customers.insertOne(
{ name: "Abhi", age: 34, cars: [ "BMW 320d", "Audi R8" ] }
)
> use tutorialkart
switched to db tutorialkart
> db.customers.insertOne(
... { name: "Abhi", age: 34, cars: [ "BMW 320d", "Audi R8" ] }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("59e5a68e2ecc0bac28144394")
}
>
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
use tutorialkart
db.customers.insertMany(
[
{ 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 above command insert following multiple documents to the customers collection.
– { 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” ] }
> use tutorialkart
switched to db tutorialkart
> db.customers.insertMany(
... [
... { 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" ] }
... ]
... )
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("59e5bf0f2ecc0bac28144395"),
ObjectId("59e5bf0f2ecc0bac28144396"),
ObjectId("59e5bf0f2ecc0bac28144397")
]
}
>
The response to the console, “acknowledged” : true meaning documents are inserted successfully, and the corresponding object ids are provided in insertedIds.
Conclusion
In this MongoDB Tutorial, we learned how to insert document(s) to a MongoDB Collection.