Insert Data in MongoDB

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to insert data into MongoDB using various methods and explore basic data manipulation techniques. Through a series of hands-on exercises, you'll practice inserting single and multiple documents, handling potential errors, and verifying data integrity using the MongoDB shell.

The lab covers essential CRUD (Create, Read, Update, Delete) operations, focusing on document insertion strategies. You'll create a bookstore database, insert documents with different structures, handle unique index constraints, and validate document schemas. By the end of this lab, you'll have a solid understanding of how to effectively add and manage data in MongoDB.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/IndexingGroup(["`Indexing`"]) mongodb(("`MongoDB`")) -.-> mongodb/ErrorHandlingGroup(["`Error Handling`"]) mongodb(("`MongoDB`")) -.-> mongodb/RelationshipsGroup(["`Relationships`"]) mongodb/BasicOperationsGroup -.-> mongodb/create_database_collection("`Create Database and Collection`") mongodb/BasicOperationsGroup -.-> mongodb/insert_document("`Insert Document`") mongodb/BasicOperationsGroup -.-> mongodb/bulk_insert_documents("`Bulk Insert Documents`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/QueryOperationsGroup -.-> mongodb/project_fields("`Project Fields`") mongodb/IndexingGroup -.-> mongodb/create_index("`Create Index`") mongodb/ErrorHandlingGroup -.-> mongodb/handle_write_errors("`Handle Write Errors`") mongodb/RelationshipsGroup -.-> mongodb/create_document_references("`Create Document References`") subgraph Lab Skills mongodb/create_database_collection -.-> lab-420696{{"`Insert Data in MongoDB`"}} mongodb/insert_document -.-> lab-420696{{"`Insert Data in MongoDB`"}} mongodb/bulk_insert_documents -.-> lab-420696{{"`Insert Data in MongoDB`"}} mongodb/find_documents -.-> lab-420696{{"`Insert Data in MongoDB`"}} mongodb/query_with_conditions -.-> lab-420696{{"`Insert Data in MongoDB`"}} mongodb/project_fields -.-> lab-420696{{"`Insert Data in MongoDB`"}} mongodb/create_index -.-> lab-420696{{"`Insert Data in MongoDB`"}} mongodb/handle_write_errors -.-> lab-420696{{"`Insert Data in MongoDB`"}} mongodb/create_document_references -.-> lab-420696{{"`Insert Data in MongoDB`"}} end

Insert Single Document

Welcome to the MongoDB Hands-on Lab! In this first step, we'll explore how to insert documents into a MongoDB collection. MongoDB is a powerful NoSQL database that stores data in flexible, JSON-like documents, making it incredibly versatile for various application needs.

Understanding MongoDB Basics

Before we begin, let's briefly discuss what we'll be doing. We'll create a bookstore database and learn how to insert documents representing books. This will help you understand the fundamental document insertion techniques in MongoDB.

Connect to MongoDB

First, open a terminal and connect to MongoDB using mongosh:

mongosh

You should see the MongoDB shell prompt, indicating a successful connection.

Create a Database and Collection

Let's create a new database called bookstore and a collection named books:

use bookstore
db.createCollection("books")

Example output:

switched to db bookstore
{ ok: 1 }

Insert a Single Document

Now, let's insert a single document representing a book into the books collection:

db.books.insertOne({
  title: "The Great Gatsby",
  author: "F. Scott Fitzgerald",
  year: 1925,
  genres: ["Classic", "Fiction"]
})

Example output:

{
  acknowledged: true,
  insertedId: ObjectId("...unique-object-id...")
}

Notice how MongoDB automatically generates a unique _id for each document. This helps ensure each document can be uniquely identified in the collection.

Bulk Insert Documents

In this step, we'll expand our bookstore collection by learning how to insert multiple documents simultaneously. Bulk insertion is an efficient way to add multiple records in a single operation.

Prepare for Bulk Insertion

We'll continue working in the bookstore database and add multiple book documents at once:

use bookstore

Insert Multiple Documents

Use the insertMany() method to add several book documents:

db.books.insertMany([
  {
    title: "1984",
    author: "George Orwell",
    year: 1949,
    genres: ["Dystopian", "Science Fiction"]
  },
  {
    title: "To Kill a Mockingbird",
    author: "Harper Lee",
    year: 1960,
    genres: ["Classic", "Fiction"]
  },
  {
    title: "Pride and Prejudice",
    author: "Jane Austen",
    year: 1813,
    genres: ["Romance", "Classic"]
  }
])

Example output:

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

Verify Inserted Documents

Let's confirm the number of documents in the collection:

db.books.countDocuments()

Example output:

4

This shows we now have 4 documents in our collection.

Check Insert Results

In this step, we'll explore how to retrieve and examine the documents we've inserted into our MongoDB collection. This is crucial for verifying data and performing queries.

Find All Documents

Use the find() method to retrieve all documents in the books collection:

use bookstore
db.books.find()

Example output will display all document details with their full information.

Find Specific Documents

Retrieve documents using specific criteria:

## Find books published before 1950
db.books.find({ year: { $lt: 1950 } })

Example output will show books published before 1950.

Find Documents with Specific Fields

Retrieve specific fields from documents:

## Find titles and authors of classic books
db.books.find(
  { genres: "Classic" },
  { title: 1, author: 1, _id: 0 }
)

This command returns only titles and authors of classic books, excluding the _id field.

Handle Insert Errors

In this step, we'll learn how to handle potential errors when inserting documents, which is essential for maintaining data integrity in your MongoDB database.

Create a Unique Index

First, create a unique index on the title field to prevent duplicate book titles:

use bookstore
db.books.createIndex({ title: 1 }, { unique: true })

Example output:

title_1

Attempt to Insert a Duplicate Document

Try inserting a document with a title that already exists:

db.books.insertOne({
  title: "1984",
  author: "George Orwell",
  year: 1949,
  genres: ["Dystopian", "Science Fiction"]
})

This will result in a duplicate key error.

Handle Insertion Errors with try-catch

Use error handling to manage insertion attempts:

try {
  db.books.insertOne({
    title: "1984",
    author: "George Orwell",
    year: 1949,
    genres: ["Dystopian", "Science Fiction"]
  })
} catch (e) {
  print("Error inserting document:", e.message)
}

This approach demonstrates graceful error handling during document insertion.

Verify Data Integrity

In our final step, we'll verify the data integrity of our MongoDB collection, ensuring our documents are stored correctly and meet our defined criteria.

Count Documents

Verify the total number of documents:

use bookstore
db.books.countDocuments()

Check Specific Document Existence

Use findOne() to verify a specific document:

db.books.findOne({ title: "To Kill a Mockingbird" })

Validate Collection Schema

Create a validation rule to ensure document structure:

db.runCommand({
  collMod: "books",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["title", "author", "year"],
      properties: {
        title: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        author: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        year: {
          bsonType: "int",
          minimum: 1000,
          maximum: 2023,
          description: "must be an integer between 1000 and 2023"
        }
      }
    }
  }
})

This step ensures that our documents maintain a consistent and valid structure.

Summary

In this lab, you successfully learned how to insert documents into MongoDB using various techniques. You started by inserting a single document, then progressed to bulk insertions with multiple documents. You explored methods to find and retrieve documents, handle potential insertion errors, and validate data integrity using unique indexes and JSON schema validation.

Key skills you acquired include using insertOne() and insertMany() methods, creating unique indexes, implementing error handling strategies, and verifying document structures. These fundamental CRUD operations provide a solid foundation for working with MongoDB, enabling you to effectively manage and manipulate data in NoSQL databases.

Other MongoDB Tutorials you may like