db.students.insertOne({ ... })adds one document.db.students.insertMany([{ ... }, { ... }])adds several.- If you leave out
_id, MongoDB generates anObjectId.
MongoDB Insert
insertOne and insertMany.
✍️ 2 exercises in this lessonKey Takeaways: MongoDB Insert
Mastering MongoDB Insert helps you write clean and reliable MongoDB code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
MongoDB Insert Code Example
MongoDBdb.students.insertOne({ name: "Ali", city: "Lahore", marks: 81 })
db.students.insertMany([
{ name: "Sara", city: "Karachi", marks: 94 },
{ name: "Usman", city: "Islamabad", marks: 67 }
])
Output
{ acknowledged: true, insertedId: ObjectId('66f1...') }
{ acknowledged: true, insertedIds: { '0': ObjectId('66f1...'), '1': ObjectId('66f1...') } }
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
MongoDB Insert Practice Exercises
Check what you learned in “MongoDB Insert”.
/ 2 solved
Fill in the blank
Insert several documents at once.
db.products.([{ name: "Pen" }, { name: "Book" }])
✓ Correct!
Not quite. Try again.
Multiple choice
What happens if you insert a document without _id?
✓ Correct!
Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services