MongoDB - Getting StartedMongoDB - Getting Started1

Insert Operations in MongoDB



Insert Operations in MongoDB

In MongoDB, inserting data means adding new documents to a collection. You don't need to predefine the schema or structure of your data, making it flexible and fast to use. MongoDB provides two main methods for insert operations:

How to Use insertOne()

This method is used to insert a single document into a collection. If the collection doesn’t exist yet, MongoDB will automatically create it for you.

Step-by-step:

  1. Start the MongoDB shell
  2. Select or create your database
  3. Use insertOne() to insert a document

Example 1: Insert One User Document


    mongo
    

    use mydb
    db.users.insertOne({
      name: "Alice",
      age: 25,
      email: "alice@example.com"
    });
    

Output:

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

Explanation: The document is inserted into the users collection. MongoDB auto-generates a unique _id field for each document if not provided.

Intuition Check

Q: What happens if the users collection doesn't exist yet?

A: MongoDB will automatically create the collection when you insert the first document. You don’t need to explicitly create it beforehand.

How to Use insertMany()

This method is used to insert multiple documents into a collection in one operation. It's more efficient than calling insertOne() multiple times.

Example 2: Insert Multiple Product Documents


    db.products.insertMany([
      {
        name: "Laptop",
        brand: "Dell",
        price: 70000
      },
      {
        name: "Phone",
        brand: "Samsung",
        price: 30000
      },
      {
        name: "Tablet",
        brand: "Apple",
        price: 50000
      }
    ]);
    

Output:

    {
      acknowledged: true,
      insertedIds: {
        "0": ObjectId("..."),
        "1": ObjectId("..."),
        "2": ObjectId("...")
      }
    }
    

Explanation: Each document in the array is inserted into the products collection. The insertedIds map shows the index and ID of each inserted document.

Intuition Check

Q: Can documents inserted with insertMany() have different fields?

A: Yes! MongoDB allows documents with different fields in the same collection. It doesn’t enforce a fixed schema.

Insert with Custom _id Field

You can also specify your own _id field if you want full control over the document identifier.

Example 3: Insert Document with Custom _id


    db.users.insertOne({
      _id: "user123",
      name: "Bob",
      age: 28
    });
    

Output:

    {
      acknowledged: true,
      insertedId: "user123"
    }
    

Explanation: The document uses a custom string _id instead of the default ObjectId. This can be useful when integrating with external systems that use predefined IDs.

Intuition Check

Q: What happens if you insert another document with the same _id?

A: MongoDB will throw a duplicate key error. The _id must be unique within the collection.

Summary

In the next topic, we will learn how to read documents from the collection using powerful querying features like find() and filters.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M