CRUD OperationsCore· 30 min read

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.

insertOne and insertMany
// 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.

  1. You hand MongoDB an object (or an array of objects).
  2. MongoDB adds a unique _id to any document that does not already have one.
  3. It stores each document in the collection (creating the collection if it is the first insert).
  4. 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?

Answer: insertMany([...]) inserts an array of documents in one call. insertOne adds a single document.

✍️ Practice

  1. Insert one user document, then insert three more with insertMany.
  2. Insert documents where some have extra fields others do not.

🏠 Homework

  1. Insert five product documents (name, price, inStock) into a products collection.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →