Inserting Documents

View saved

Insert one

insertOne adds a single document and returns the new _id.

db.books.insertOne({
  title: "Practical MongoDB",
  year: 2024,
  tags: ["database", "nosql"]
})

Insert many

Pass an array. Use ordered inserts carefully: a duplicate key can stop the rest of the batch.

db.books.insertMany([
  { title: "Learn Indexes", year: 2023 },
  { title: "Aggregation Recipes", year: 2025 }
])

Validate before bulk loads

Check required fields in application code. Schema validation rules on the collection are available when you need server-side guards.

Idempotent practice

For learning, delete test collections freely. In apps, design inserts so retries do not create unwanted duplicates (unique indexes help).

Comments

One comment per signed-in account. Comments are saved with this page’s URL.