Lesson 11 of 50 – Inserting Documents in MongoDB
22%

Inserting Documents in MongoDB

In MongoDB, documents are used to store data inside collections. We can insert a single document or multiple documents using MongoDB Shell (mongosh). In this lesson, you will learn insertOne(), insertMany(), document structure, and how to verify inserted records.

1. What Is Document Insertion?

Document insertion means adding new data to a MongoDB collection. A document contains fields and their values, similar to a record in a relational database.

Example document:

{
    name: "Rahul",
    age: 20,
    course: "ADCA"
}

Here, name, age, and course are fields.

MongoDB stores documents in BSON format and normally generates a unique _id field automatically when you do not provide one.

2. Prepare the Database and Collection

First, select a database named school.

use school

Create the students collection if it does not already exist.

db.createCollection("students")

If the collection already exists, you can continue using it without creating it again. MongoDB can also create a collection automatically when you first insert data into it.

3. Insert One Document Using insertOne()

The insertOne() method inserts one document into a collection.

db.students.insertOne({
    name: "Rahul",
    age: 20,
    course: "ADCA",
    city: "Aurangabad"
})

Example of a successful response:

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

The generated insertedId identifies the newly inserted document. Its exact value will differ each time.

Verify the Inserted Document
db.students.find()

This command displays documents stored in the students collection.

4. Insert Multiple Documents Using insertMany()

Use insertMany() when you want to insert several documents in one operation.

db.students.insertMany([
    {
        name: "Amit",
        age: 21,
        course: "Tally Prime",
        city: "Patna"
    },
    {
        name: "Priya",
        age: 19,
        course: "Web Development",
        city: "Gaya"
    },
    {
        name: "Neha",
        age: 22,
        course: "Python",
        city: "Aurangabad"
    }
])

The square brackets [] contain an array of documents. Each document is enclosed in curly braces {}.

Display All Documents
db.students.find()
Count All Documents
db.students.countDocuments({})

The count includes all documents currently in the collection, including any records inserted earlier.

5. Insert Documents with Different Data Types

MongoDB documents can contain strings, numbers, Boolean values, arrays, nested documents, and dates.

db.students.insertOne({
    name: "Suman",
    age: 20,
    feesPaid: 5000,
    active: true,
    skills: ["HTML", "CSS", "JavaScript"],
    address: {
        city: "Patna",
        state: "Bihar"
    },
    admissionDate: new Date()
})

In this example:

  • name is a string.
  • age and feesPaid are numbers.
  • active is a Boolean value.
  • skills is an array.
  • address is a nested document.
  • admissionDate is a date value.

6. Insert a Document with a Custom _id

MongoDB normally generates an _id automatically. You can also supply your own unique value.

db.students.insertOne({
    _id: "STU101",
    name: "Ravi",
    age: 21,
    course: "Python"
})

You can retrieve this document using its custom ID:

db.students.findOne({
    _id: "STU101"
})

Important: Each document in a collection must have a unique _id. Inserting another document with the same ID will normally result in a duplicate-key error.

7. Insert Documents with Conditional Data

You can store additional fields whenever required. Documents in the same collection do not all need to have exactly the same fields.

db.students.insertMany([
    {
        name: "Anjali",
        course: "ADCA",
        feesPaid: 3000
    },
    {
        name: "Vikas",
        course: "Python",
        feesPaid: 5000,
        scholarship: true
    }
])

The second document contains an extra field named scholarship. This flexibility is one of MongoDB's useful features.

Find students whose scholarship value is true:

db.students.find({
    scholarship: true
})

8. Common Insertion Errors

Error 1: Duplicate _id

A duplicate _id can cause an insertion to fail because each document needs a unique ID.

Error 2: Incorrect Syntax

Check commas, quotation marks, brackets, and braces. Each field must have a valid value.

Error 3: Wrong Collection Name

Confirm that you are inserting into the intended collection, such as db.students.

Error 4: Incorrect Data Type

Make sure that values use the intended type. For example, use age: 20 for a numeric age rather than age: "20" if you want a number.

9. insertOne() vs insertMany()

Feature insertOne() insertMany()
Purpose Insert one document Insert multiple documents
Input One document object An array of documents
Example db.students.insertOne({...}) db.students.insertMany([{...}])
Common use Register one student Import several student records

10. Complete Practical Example

Run the following commands in order to practise inserting and verifying documents.

Step 1: Select the Database
use school
Step 2: Insert One Document
db.students.insertOne({
    name: "Karan",
    age: 20,
    course: "JavaScript"
})
Step 3: Insert Two More Documents
db.students.insertMany([
    {
        name: "Pooja",
        age: 19,
        course: "HTML"
    },
    {
        name: "Manish",
        age: 22,
        course: "Python"
    }
])
Step 4: Display All Documents
db.students.find().pretty()
Step 5: Find a Particular Course
db.students.find({
    course: "Python"
})
Step 6: Count the Documents
db.students.countDocuments({})

These commands demonstrate how to insert, retrieve, filter, and count student documents.

📝 Practical Assignment

Create a database named college and practise inserting documents into a collection named students.

  1. Insert one student using insertOne().
  2. Insert five students using insertMany().
  3. Include name, age, course, and city fields.
  4. Insert a document containing an array of skills.
  5. Insert a document with a nested address object.
  6. Insert a document using a custom _id.
  7. Display all inserted documents.
  8. Count all documents in the collection.
  9. Find all students enrolled in Python.

🧠 Quick Quiz

1. Which method inserts one document?


2. Which method inserts multiple documents?


3. What happens if you do not provide _id?