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.
In MongoDB, a document is inserted as a BSON document. If the document does not contain an _id field, MongoDB automatically adds one with an ObjectId value. You can insert documents from the MongoDB shell using insertOne() for a single document and insertMany() for a list of documents.
- Insert Single Document
- Insert Multiple Documents
- Insert a Document with a Custom _id
- Check Inserted Documents
- MongoDB Insert Document FAQs
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).
The value of insertedId is the _id of the new document. In most examples, MongoDB creates this value automatically. If you supply your own _id, the value must be unique in the collection.
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.
With insertMany(), pass an array of documents. The result contains insertedIds, which maps each inserted document position to the _id created or supplied for that document.
Insert a MongoDB Document with a Custom _id Field
MongoDB automatically creates an _id field when it is missing. You may also provide your own _id value. This is useful when the document must use an application-generated identifier, such as a customer number or external system ID.
db.customers.insertOne({
_id: "CUST-1001",
name: "Ravi",
age: 29,
place: "Hyderabad"
})
If another document already has the same _id, MongoDB returns a duplicate key error and does not insert that document.
Check MongoDB Documents After insertOne() or insertMany()
After inserting documents, use find() to read them from the collection. The following command returns all documents from the customers collection.
db.customers.find()
To make the output easier to read in the shell, use pretty().
db.customers.find().pretty()
MongoDB insertOne() vs insertMany()
| Method | Use it when | Input | Result field |
|---|---|---|---|
db.collection.insertOne() | You want to insert one document into a collection. | One document object | insertedId |
db.collection.insertMany() | You want to insert two or more documents in one command. | Array of document objects | insertedIds |
For new MongoDB shell examples, insertOne() and insertMany() are preferred because their intent is clear. The older db.collection.insert() method can insert one document or an array of documents, but it is less explicit for beginners.
Common MongoDB Insert Document Errors
While inserting documents into a MongoDB collection, check these common issues.
- Duplicate _id: every document in a collection must have a unique
_id. - Missing array brackets in insertMany():
insertMany()expects an array of documents, not separate document arguments. - Invalid document syntax: field names and values must form a valid JavaScript object in the MongoDB shell.
- Wrong database selected: run
dbin the shell to confirm the current database before inserting.
MongoDB Insert Document Reference Links
For more details about insert operations, refer to the MongoDB documentation for insert documents in MongoDB Shell, insert documents tutorial, and db.collection.insertMany().
MongoDB Insert Document FAQs
Which MongoDB method inserts one document into a collection?
Use db.collection.insertOne() to insert one document into a MongoDB collection. The response contains acknowledged and insertedId.
Which MongoDB method inserts multiple documents?
Use db.collection.insertMany() to insert multiple documents. Pass the documents as an array, and MongoDB returns the inserted document IDs in insertedIds.
Does MongoDB create the collection during insert?
Yes. If the database exists and the collection name does not already exist, MongoDB can create the collection when the first document is inserted.
What happens if I insert a document without _id in MongoDB?
If the inserted document does not contain an _id field, MongoDB adds one automatically. The generated value is usually an ObjectId.
Can insertMany() insert documents with different fields?
Yes. Documents in the same MongoDB collection can have different fields. For example, one customer document may contain place, while another may not.
MongoDB Insert Document Editorial QA Checklist
- Confirm that the tutorial clearly explains when to use
insertOne()and when to useinsertMany(). - Check that every MongoDB shell command uses the same database and collection names used in the explanation.
- Verify that the response fields
acknowledged,insertedId, andinsertedIdsare described correctly. - Ensure that custom
_idbehavior and duplicate key errors are mentioned without overcomplicating the beginner example. - Review all newly added code blocks for the correct PrismJS language classes.
Conclusion
In this MongoDB Tutorial, we learned how to insert document(s) to a MongoDB Collection.
TutorialKart.com