CPCODELAB
MongoDB

Inserting Documents

9 min read

insertOne and insertMany

You add documents to a collection with insertOne (a single document) or insertMany (an array of documents). Both operations return metadata including the generated _id values.

insertOne

js
// mongosh
db.students.insertOne({
  name: "Riya Sharma",
  age: 20,
  course: "Full Stack",
  enrolled: true,
  tags: ["frontend", "react"]
});

// Returns: { acknowledged: true, insertedId: ObjectId(...) }

insertMany

js
db.students.insertMany([
  { name: "Aman Verma", age: 22, course: "Data Science", enrolled: true },
  { name: "Priya Singh", age: 19, course: "Full Stack", enrolled: false },
  { name: "Karan Mehta", age: 21, course: "DevOps", enrolled: true }
]);

// Returns insertedCount: 3

If any document in insertMany fails validation, MongoDB rolls back only that document by default (unordered insert). Pass { ordered: true } to stop on the first error.

Ready to test yourself?
Practice MongoDB— quiz & coding exercises