Create
Learn how to insert documents into MongoDB using insertOne and insertMany with real school system examples.
Create
The first operation in CRUD is Create — inserting new documents into a collection. MongoDB gives you two methods for this:
insertOne()— insert a single documentinsertMany()— insert multiple documents at once
insertOne
insertOne() inserts a single document into a collection. If the collection does not exist yet, MongoDB creates it automatically.
Syntax
db.collection.insertOne(document)Example — Insert a student
db.students.insertOne({
name: "Ali Hassan",
age: 16,
grade: "10th",
subjects: ["Math", "Physics", "English"],
enrolled: true,
enrollmentDate: new Date("2024-09-01"),
address: {
city: "Lahore",
country: "Pakistan"
}
})Result
{
acknowledged: true,
insertedId: ObjectId("64a1f2c3e4b0a1b2c3d4e5f6")
}MongoDB confirms the insert with two things:
acknowledged: true— the database received and saved the documentinsertedId— the_idof the newly inserted document
The _id Field
Every document must have an _id field. It is the unique identifier for that document — no two documents in the same collection can have the same _id.
If you do not provide an _id, MongoDB automatically generates an ObjectId for you. This is what happens in the example above.
You can also provide your own _id if you want:
db.students.insertOne({
_id: "student-001",
name: "Sara Ahmed",
age: 15,
grade: "9th"
})Now the _id is "student-001" instead of an ObjectId. This works, but be careful — if you try to insert another document with the same _id, MongoDB will throw an error.
In most cases, let MongoDB generate the _id automatically. ObjectIds are guaranteed to be unique, sortable by time, and work great as identifiers. Only use a custom _id when you have a specific reason — like using a student roll number as the ID.
insertMany
insertMany() inserts multiple documents in one go. It is much faster than calling insertOne() in a loop because it sends all documents to MongoDB in a single network request.
Syntax
db.collection.insertMany([document1, document2, ...])Example — Insert multiple students
db.students.insertMany([
{
name: "Umar Farooq",
age: 17,
grade: "11th",
subjects: ["Biology", "Chemistry", "English"],
enrolled: true,
enrollmentDate: new Date("2024-09-01")
},
{
name: "Ayesha Khan",
age: 15,
grade: "9th",
subjects: ["Math", "Computer Science", "English"],
enrolled: true,
enrollmentDate: new Date("2024-09-01")
},
{
name: "Bilal Ahmed",
age: 16,
grade: "10th",
subjects: ["Physics", "Math", "Urdu"],
enrolled: false,
enrollmentDate: new Date("2024-09-01")
}
])Result
{
acknowledged: true,
insertedCount: 3,
insertedIds: {
'0': ObjectId("64a1f2c3e4b0a1b2c3d4e5f7"),
'1': ObjectId("64a1f2c3e4b0a1b2c3d4e5f8"),
'2': ObjectId("64a1f2c3e4b0a1b2c3d4e5f9")
}
}MongoDB tells you how many documents were inserted and gives you the _id of each one.
Insert Teachers and Courses
Let's also populate the other collections in our school system.
Insert teachers
db.teachers.insertMany([
{
name: "Mr. Khan",
age: 45,
subject: "Math",
email: "khan@school.com",
joinedDate: new Date("2015-08-01"),
active: true
},
{
name: "Ms. Fatima",
age: 38,
subject: "Biology",
email: "fatima@school.com",
joinedDate: new Date("2018-03-15"),
active: true
},
{
name: "Mr. Raza",
age: 52,
subject: "Physics",
email: "raza@school.com",
joinedDate: new Date("2010-01-10"),
active: true
}
])Insert courses
db.courses.insertMany([
{
title: "Mathematics",
code: "MATH-10",
grade: "10th",
credits: 4,
teacherName: "Mr. Khan",
totalStudents: 30
},
{
title: "Physics",
code: "PHY-10",
grade: "10th",
credits: 4,
teacherName: "Mr. Raza",
totalStudents: 28
},
{
title: "Biology",
code: "BIO-11",
grade: "11th",
credits: 4,
teacherName: "Ms. Fatima",
totalStudents: 25
}
])Our school database now has three populated collections — students, teachers, and courses.
Ordered vs Unordered Inserts
When you use insertMany() and one of the documents fails — for example because it has a duplicate _id — MongoDB needs to decide what to do with the remaining documents.
This is controlled by the ordered option.
Ordered inserts (default)
By default, insertMany() runs in ordered mode. It inserts documents one by one in order. If one fails, it stops immediately and does not insert the remaining documents.
db.students.insertMany([
{ _id: "s001", name: "Ali Hassan" },
{ _id: "s001", name: "Duplicate ID" }, // this will fail
{ _id: "s003", name: "Ayesha Khan" } // this will NOT be inserted
])The third document never gets inserted because MongoDB stopped at the second one.
Unordered inserts
With ordered: false, MongoDB tries to insert all documents regardless of failures. Documents that succeed get inserted, failed ones are skipped.
db.students.insertMany([
{ _id: "s001", name: "Ali Hassan" },
{ _id: "s001", name: "Duplicate ID" }, // this will fail
{ _id: "s003", name: "Ayesha Khan" } // this WILL be inserted
], { ordered: false })Now the third document gets inserted even though the second one failed.
Use ordered: false when you are inserting a large batch of documents and you want as many to succeed as possible — even if some fail. Use the default ordered mode when you need all documents to insert successfully or none at all.
What Happens if an Insert Fails
If insertOne() fails, MongoDB throws an error. The most common reasons:
Duplicate _id — you tried to insert a document with an _id that already exists:
MongoServerError: E11000 duplicate key error collection: school.students index: _id_ dup keyValidation error — if you have set up schema validation rules on the collection and the document does not follow them. We cover validation in the Schema Design section.
Always wrap inserts in a try/catch in your Node.js code:
try {
await students.insertOne({
_id: "s001",
name: "Ali Hassan",
age: 16
});
console.log("Student inserted");
} catch (error) {
console.error("Insert failed:", error.message);
}insertOne vs insertMany
insertOne | insertMany | |
|---|---|---|
| Documents | 1 | Multiple |
| Speed | One network request | One network request for all |
| On failure | Throws error | Depends on ordered option |
| Returns | insertedId | insertedCount + insertedIds |
When inserting multiple documents, always prefer insertMany() over calling insertOne() in a loop. A single insertMany() call is significantly faster because it only makes one round trip to the database instead of one per document.