MongoDb - inserting

In MongoDB, documents are stored in collections, and you insert documents using methods like insertOne() and insertMany().


1. Insert a Single Document

db.users.insertOne({ name: "Alice", age: 25, email: "[email protected]" })
  • Creates the collection users if it doesn’t exist.

  • Each document automatically gets a unique _id field (ObjectId by default) if you don’t provide one.

Example result:

{
  "acknowledged": true,
  "insertedId": ObjectId("64c9c2d1a45b8e...")
}

2. Insert Multiple Documents

db.users.insertMany([
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 22, email: "[email protected]" }
])

Result:

{
  "acknowledged": true,
  "insertedIds": {
    "0": ObjectId("64c9c2d1a45b8e..."),
    "1": ObjectId("64c9c2d1a45b8f...")
  }
}

3. Specify a Custom _id (Optional)

db.users.insertOne({ _id: 1001, name: "David", age: 28 })
  • If _id already exists → MongoDB throws a duplicate key error.


4. Insert with Nested Documents & Arrays

MongoDB allows complex JSON-like structures:

db.orders.insertOne({
  orderId: 123,
  customer: { name: "Alice", email: "[email protected]" },
  items: [
    { product: "Laptop", qty: 1, price: 1200 },
    { product: "Mouse", qty: 2, price: 25 }
  ],
  status: "pending"
})

5. Insert with Write Concerns (Optional)

You can control acknowledgment behavior:

db.users.insertOne(
  { name: "Eve", age: 29 },
  { writeConcern: { w: "majority", wtimeout: 5000 } }
)

6. Legacy Command (insert)

Older versions of MongoDB used insert() (still works, but not recommended):

db.users.insert({ name: "Frank", age: 35 })

Better to use insertOne() or insertMany().


7. Verifying Insertions

To check inserted documents:

db.users.find()
  • insertOne(document) → insert a single document.

  • insertMany([documents]) → insert multiple at once.

  • MongoDB auto-creates collection on first insert.

  • Documents can be nested objects or arrays.

  • _id is always unique and automatically generated if not provided.