Inserting Documents
Add data to your database — one document or many at once.
What you will learn
- Insert one document
- Insert many documents
- Understand what is returned
insertOne and insertMany
CRUD is the four things every app does with data: Create, Read, Update and Delete. (Just remember those four words — create new data, read it back, update it, delete it.) This unit covers all four. We start with Create.
Inserting is the C in CRUD — it means *create*: putting new data into the database. There are two methods. Use insertOne(...) when you have a single document to add, and insertMany([...]) when you have several and want to add them all in one go.
// Insert a single document
db.users.insertOne({ name: "Asha", age: 22, city: "Bengaluru" })
// Insert several at once
db.users.insertMany([
{ name: "Ravi", age: 25 },
{ name: "Meera", age: 23 }
])Walking through it: db.users means “the users collection in the current database”. insertOne takes one object and stores it. insertMany takes an array of objects [ {…}, {…} ] and stores them all together — that is faster than calling insertOne many times. The objects you pass are exactly what gets saved.
Note: Output:
{ acknowledged: true, insertedId: ObjectId('65f...a1') }
{ acknowledged: true, insertedIds: { '0': ObjectId('65f...b2'), '1': ObjectId('65f...c3') } }
insertOne returns the single _id it created; insertMany returns one _id for each document (here, two). Seeing acknowledged: true means the database accepted and stored your data.
- You hand MongoDB an object (or an array of objects).
- MongoDB adds a unique
_idto any document that does not already have one. - It stores each document in the collection (creating the collection if it is the first insert).
- It returns the generated
_id(s) so you can refer back to the new data.
Tip: Documents in the same collection do not need identical fields. Ravi has no city and that is fine — MongoDB’s flexible schema allows it.
Q. Which method adds several documents at once?
✍️ Practice
- Insert one user document, then insert three more with
insertMany. - Insert documents where some have extra fields others do not.
🏠 Homework
- Insert five product documents (name, price, inStock) into a
productscollection.