Use MongoDB Basic Types

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to work with various data types in MongoDB, including numbers, strings, booleans, dates, and object IDs. The lab covers practical examples of how to store, query, and manipulate data of different types in your MongoDB database. You will gain hands-on experience in performing common operations and understanding the appropriate use cases for each data type.

The lab is divided into five main steps: working with numbers, handling string data, using boolean values, storing date and time, and managing object IDs. Each step provides a detailed walkthrough, demonstrating the relevant MongoDB commands and showcasing the unique characteristics and applications of the respective data types.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/DataTypesGroup(["`Data Types`"]) mongodb(("`MongoDB`")) -.-> mongodb/ArrayandEmbeddedDocumentsGroup(["`Array and Embedded Documents`"]) mongodb(("`MongoDB`")) -.-> mongodb/IndexingGroup(["`Indexing`"]) mongodb(("`MongoDB`")) -.-> mongodb/RelationshipsGroup(["`Relationships`"]) mongodb/BasicOperationsGroup -.-> mongodb/insert_document("`Insert Document`") mongodb/BasicOperationsGroup -.-> mongodb/update_document("`Update Document`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/DataTypesGroup -.-> mongodb/use_numeric_data_types("`Use Numeric Data Types`") mongodb/ArrayandEmbeddedDocumentsGroup -.-> mongodb/create_embedded_documents("`Create Embedded Documents`") mongodb/IndexingGroup -.-> mongodb/create_index("`Create Index`") mongodb/RelationshipsGroup -.-> mongodb/create_document_references("`Create Document References`") subgraph Lab Skills mongodb/insert_document -.-> lab-422097{{"`Use MongoDB Basic Types`"}} mongodb/update_document -.-> lab-422097{{"`Use MongoDB Basic Types`"}} mongodb/find_documents -.-> lab-422097{{"`Use MongoDB Basic Types`"}} mongodb/query_with_conditions -.-> lab-422097{{"`Use MongoDB Basic Types`"}} mongodb/use_numeric_data_types -.-> lab-422097{{"`Use MongoDB Basic Types`"}} mongodb/create_embedded_documents -.-> lab-422097{{"`Use MongoDB Basic Types`"}} mongodb/create_index -.-> lab-422097{{"`Use MongoDB Basic Types`"}} mongodb/create_document_references -.-> lab-422097{{"`Use MongoDB Basic Types`"}} end

Work With Numbers

In this step, you'll learn how to work with numeric data types in MongoDB, exploring different ways to store and manipulate numbers in your database.

Understanding Numeric Types in MongoDB

MongoDB supports several numeric data types, including integers and floating-point numbers. Let's start by launching the MongoDB shell and exploring these types.

First, open your terminal and start the MongoDB shell:

mongosh

Now, let's create a database and collection to demonstrate numeric operations:

use numbers_lab
db.createCollection("products")

Inserting Integer and Decimal Numbers

Let's add some products with different numeric types:

db.products.insertMany([
    {
        name: "Laptop",
        price: 999,           // Integer
        stock: 50,            // Integer
        discount: 0.1,        // Decimal
        rating: 4.5           // Floating-point
    },
    {
        name: "Smartphone",
        price: 599,
        stock: 100,
        discount: 0.15,
        rating: 4.7
    }
])

Example Output

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

Numeric Operations

MongoDB allows you to perform various numeric operations. Let's demonstrate some:

// Find products with price greater than 500
db.products.find({ price: { $gt: 500 } })

// Update stock with increment
db.products.updateOne(
    { name: "Laptop" },
    { $inc: { stock: 10 } }
)

// Find products with rating above 4
db.products.find({ rating: { $gte: 4 } })

Key Points to Remember

  • Integers are whole numbers without decimal points
  • Floating-point numbers can have decimal places
  • MongoDB uses $gt (greater than), $lt (less than), $inc (increment) for numeric operations

Handle String Data

In this step, you'll learn how to work with string data types in MongoDB, exploring different ways to store, query, and manipulate text data in your database.

Understanding String Types in MongoDB

MongoDB provides powerful string handling capabilities. We'll continue using the database we created in the previous step to demonstrate string operations.

First, ensure you're in the MongoDB shell:

mongosh

Switch to the existing database:

use numbers_lab

Inserting and Querying String Data

Let's add more documents with string fields:

db.products.insertMany([
    {
        name: "Wireless Headphones",
        brand: "TechSound",
        description: "High-quality noise-canceling headphones",
        color: "Black",
        tags: ["electronics", "audio", "wireless"]
    },
    {
        name: "Smart Watch",
        brand: "FitTech",
        description: "Advanced fitness tracking smartwatch",
        color: "Silver",
        tags: ["wearables", "fitness", "technology"]
    }
])

String Query Operations

MongoDB offers various ways to query string data:

// Find products by exact name
db.products.find({ name: "Smart Watch" })

// Case-insensitive search using regex
db.products.find({ brand: { $regex: /tech/i } })

// Search in array of tags
db.products.find({ tags: "electronics" })

String Manipulation Methods

You can also perform string operations:

// Update description
db.products.updateOne(
    { name: "Wireless Headphones" },
    { $set: { description: description.toUpperCase() } }
)

// Check string length
db.products.find({
    $expr: { $gt: [{ $strLenCP: "$name" }, 10] }
})

Key Points to Remember

  • Strings in MongoDB are UTF-8 encoded
  • Use $regex for pattern matching
  • Arrays can contain string elements
  • MongoDB supports various string manipulation methods

Use Boolean Values

In this step, you'll learn how to work with Boolean data types in MongoDB, exploring how to store, query, and use true/false values in your database.

Understanding Boolean Types in MongoDB

Boolean values are crucial for representing true/false conditions in your data. We'll continue using our existing database to demonstrate Boolean operations.

First, ensure you're in the MongoDB shell:

mongosh

Switch to the existing database:

use numbers_lab

Inserting Documents with Boolean Fields

Let's add products with Boolean attributes:

db.products.insertMany([
    {
        name: "Premium Bluetooth Speaker",
        isWireless: true,
        isInStock: true,
        hasBluetooth: true,
        supportsBattery: true
    },
    {
        name: "Wired Gaming Headset",
        isWireless: false,
        isInStock: false,
        hasBluetooth: false,
        supportsBattery: false
    }
])

Boolean Query Operations

MongoDB provides powerful ways to query Boolean fields:

// Find wireless products
db.products.find({ isWireless: true })

// Find products not in stock
db.products.find({ isInStock: false })

// Complex Boolean queries
db.products.find({
    $and: [
        { isWireless: true },
        { hasBluetooth: true }
    ]
})

Updating Boolean Values

You can easily update Boolean fields:

// Update stock status
db.products.updateOne(
    { name: "Wired Gaming Headset" },
    { $set: { isInStock: true } }
)

// Toggle a Boolean value
db.products.updateOne(
    { name: "Premium Bluetooth Speaker" },
    { $not: { isWireless: true } }
)

Key Points to Remember

  • Boolean values are either true or false
  • Use logical operators like $and, $or for complex queries
  • Boolean fields are useful for flags and status tracking
  • MongoDB treats Boolean fields like any other data type

Store Date Time

In this step, you'll learn how to work with date and time data types in MongoDB, exploring various ways to store, query, and manipulate temporal data.

Understanding Date Types in MongoDB

MongoDB provides powerful date and time handling capabilities. We'll continue using our existing database to demonstrate date operations.

First, ensure you're in the MongoDB shell:

mongosh

Switch to the existing database:

use numbers_lab

Inserting Documents with Date Fields

Let's add products with different date-related fields:

db.products.insertMany([
    {
        name: "Laptop Pro",
        releaseDate: new Date(),
        lastUpdated: new Date(),
        warrantyExpiration: new Date("2025-12-31"),
        manufacturingDate: new Date("2023-01-15")
    },
    {
        name: "Smartphone Elite",
        releaseDate: new Date("2023-06-01"),
        lastUpdated: new Date(),
        warrantyExpiration: new Date("2024-06-01"),
        manufacturingDate: new Date("2023-05-15")
    }
])

Date Query Operations

MongoDB offers sophisticated date querying capabilities:

// Find products released after a specific date
db.products.find({
    releaseDate: { $gt: new Date("2023-01-01") }
})

// Find products with warranty expiring in the next year
db.products.find({
    warrantyExpiration: {
        $gte: new Date(),
        $lt: new Date(new Date().setFullYear(new Date().getFullYear() + 1))
    }
})

// Get products manufactured in a specific month
db.products.find({
    $expr: {
        $eq: [{ $month: "$manufacturingDate" }, 5]
    }
})

Date Manipulation Methods

You can perform various date-related operations:

// Update last updated date
db.products.updateOne(
    { name: "Laptop Pro" },
    { $currentDate: { lastUpdated: true } }
)

// Add days to a date
db.products.updateOne(
    { name: "Smartphone Elite" },
    {
        $set: {
            extendedWarranty: new Date(
                new Date("2024-06-01").setDate(
                    new Date("2024-06-01").getDate() + 30
                )
            )
        }
    }
)

Key Points to Remember

  • MongoDB stores dates as full date objects
  • Use new Date() to create current timestamp
  • Compare dates using comparison operators
  • MongoDB provides methods to extract date components
  • Dates are stored in UTC by default

Manage ObjectIds

In this step, you'll learn about ObjectIds in MongoDB, understanding how they work as unique identifiers and how to manipulate them in your database.

Understanding ObjectIds in MongoDB

ObjectIds are special identifiers automatically generated by MongoDB for each document. We'll explore their characteristics and usage.

First, ensure you're in the MongoDB shell:

mongosh

Switch to the existing database:

use numbers_lab

Creating and Examining ObjectIds

Let's insert documents and examine their unique identifiers:

// Insert a document and observe its ObjectId
db.users.insertOne({
    username: "johndoe",
    email: "[email protected]",
    registrationDate: new Date()
})

// Retrieve the inserted document
const newUser = db.users.findOne({ username: "johndoe" })

ObjectId Properties and Methods

ObjectIds contain several interesting properties:

// Get the timestamp of the ObjectId
const timestamp = newUser._id.getTimestamp()
print("Document created at:", timestamp)

// Generate a new ObjectId
const customId = new ObjectId()
print("Custom ObjectId:", customId)

Working with ObjectIds in Queries

You can use ObjectIds for precise document retrieval:

// Find document by its exact ObjectId
db.users.findOne({ _id: newUser._id })

// Check if an ObjectId is valid
const isValid = ObjectId.isValid(newUser._id)
print("Is ObjectId valid?", isValid)

Advanced ObjectId Operations

MongoDB provides methods to extract and manipulate ObjectIds:

// Compare ObjectIds
const anotherUser = db.users.insertOne({
    username: "janedoe",
    email: "[email protected]"
})

// Check if one ObjectId is less than another
const isEarlier = newUser._id < anotherUser.insertedId
print("Is first user's ID earlier?", isEarlier)

Key Points to Remember

  • ObjectIds are unique 12-byte identifiers
  • They contain a timestamp, machine identifier, process ID, and random value
  • Every document gets an automatic ObjectId if not specified
  • ObjectIds can be used for sorting and tracking document creation time

Summary

In this lab, you learned how to work with different numeric data types in MongoDB, including integers and floating-point numbers. You explored ways to insert, query, and update numeric data, using operators like $gt, $lt, and $inc. Additionally, you gained an understanding of handling string data, working with boolean values, storing date and time information, and managing ObjectIds in your MongoDB database.

You also learned how to perform various string operations, such as querying, updating, and manipulating text data. The lab covered the usage of different string-related operators and methods provided by MongoDB to effectively work with textual information in your applications.

Other MongoDB Tutorials you may like