0 Tk

Inserting Documents

MongoDB provides several methods for inserting documents into a collection:

  1. insertOne(): Inserts a single document into a collection. Example:

    db.users.insertOne({
      name: 'John Doe',
      age: 30,
      email: 'john@example.com'
    })
    
  2. insertMany(): Inserts multiple documents into a collection. Example:

    db.users.insertMany([
      { name: 'Jane Doe', age: 28, email: 'jane@example.com' },
      { name: 'Bob Smith', age: 35, email: 'bob@example.com' }
    ])
    
  3. insert(): A legacy method that can insert either a single document or multiple documents.

When inserting documents:

  • If the collection doesn’t exist, MongoDB creates it automatically.
  • Each document requires a unique _id field. If not provided, MongoDB generates an ObjectId for this field.
  • You can specify your own _id value, but it must be unique within the collection.

Insert operations in MongoDB are atomic at the single-document level.