Skip to content

CRUD

insertOne() and insertMany()

Writing documents, ordered versus unordered inserts, and what comes back.

BeginnerAbout 4 minutes

Insert writes new documents. insertOne for a single record. insertMany for a batch. If you omit _id, MongoDB generates an ObjectId — the same default as in Fundamentals.

db.users.insertOne({
  name: "Priya",
  age: 26,
  city: "Bangalore",
  role: "developer",
  skills: ["Node.js"],
  isActive: true
})
One user into the users collection
{
  acknowledged: true,
  insertedId: ObjectId("64a1b2c3d4e5f6a7b8c90002")
}
The server tells you the _id it stored
db.orders.insertMany([
  { userId: ObjectId("64a1b2c3d4e5f6a7b8c90001"), amount: 4500, status: "completed" },
  { userId: ObjectId("64a1b2c3d4e5f6a7b8c90001"), amount: 1200, status: "pending" }
])
Several documents in one round trip
{
  acknowledged: true,
  insertedIds: {
    0: ObjectId("64a1b2c3d4e5f6a7b8c90011"),
    1: ObjectId("64a1b2c3d4e5f6a7b8c90012")
  }
}

Ordered vs unordered

insertMany is ordered by default. If document 3 has a duplicate _id, 4 and 5 never run. Pass { ordered: false } when you want the rest to continue — bulk imports, not a money transfer.

const result = await users.insertOne({
  name: "Priya",
  city: "Bangalore",
  isActive: true,
});
// result.insertedId
Node.js — same documents, collection method

Interview question

What does insertOne return, and who creates _id?

Think about it first.

Interview question

When would you set ordered: false on insertMany?

Think about it first.