Inserting Documents

insertOne() and insertMany() add documents to a collection, and MongoDB stamps each one with a unique _id automatically if you don't supply your own.

Inserting a single document

JS mongosh
db.posts.insertOne({
  title: "Hello, MongoDB",
  author: "Priya",
  views: 0
})
Output
{
  acknowledged: true,
  insertedId: ObjectId("65f1a3104c1a2b3c4d5e6f71")
}

MongoDB generated _id for you — a unique ObjectId that acts as the document's primary key, the same role an auto-incrementing id column plays in a SQL table.

Inserting many at once

JS mongosh
db.posts.insertMany([
  { title: "Indexes Explained", author: "Sam", views: 12 },
  { title: "Schema Design 101", author: "Priya", views: 5 }
])
Output
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("65f1a3334c1a2b3c4d5e6f72"),
    '1': ObjectId("65f1a3334c1a2b3c4d5e6f73")
  }
}
Note: By default, insertMany() is ordered — if the third document in a batch of ten fails (say, a duplicate _id), MongoDB stops right there and the remaining seven never get inserted. Passing { ordered: false } as a second argument tells it to skip failures and keep going, inserting everything else that's valid.