Work With MongoDB Dates

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to work with MongoDB dates, including inserting date values, querying date ranges, formatting date output, updating date fields, and sorting by date. You will explore various methods for inserting dates, such as using the current date, creating a specific date, and using a timestamp in milliseconds. Additionally, you will learn how to query date ranges, format date output, update date fields, and sort data by date. This lab provides a comprehensive overview of working with MongoDB's date-related functionalities.


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/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/QueryOperationsGroup -.-> mongodb/sort_documents("`Sort Documents`") mongodb/QueryOperationsGroup -.-> mongodb/project_fields("`Project Fields`") mongodb/DataTypesGroup -.-> mongodb/use_numeric_data_types("`Use Numeric Data Types`") mongodb/ArrayandEmbeddedDocumentsGroup -.-> mongodb/query_embedded_documents("`Query Embedded Documents`") mongodb/RelationshipsGroup -.-> mongodb/create_document_references("`Create Document References`") subgraph Lab Skills mongodb/insert_document -.-> lab-422101{{"`Work With MongoDB Dates`"}} mongodb/update_document -.-> lab-422101{{"`Work With MongoDB Dates`"}} mongodb/find_documents -.-> lab-422101{{"`Work With MongoDB Dates`"}} mongodb/query_with_conditions -.-> lab-422101{{"`Work With MongoDB Dates`"}} mongodb/sort_documents -.-> lab-422101{{"`Work With MongoDB Dates`"}} mongodb/project_fields -.-> lab-422101{{"`Work With MongoDB Dates`"}} mongodb/use_numeric_data_types -.-> lab-422101{{"`Work With MongoDB Dates`"}} mongodb/query_embedded_documents -.-> lab-422101{{"`Work With MongoDB Dates`"}} mongodb/create_document_references -.-> lab-422101{{"`Work With MongoDB Dates`"}} end

Insert Date Values

In this step, you'll learn how to insert date values in MongoDB using the MongoDB shell (mongosh). Dates are an essential data type in databases, and MongoDB provides powerful ways to work with them.

First, let's start the MongoDB shell:

mongosh

Now, let's create a database for our date experiments:

use datelab

MongoDB allows you to insert dates in several ways. We'll explore three common methods:

  1. Using the current date:
db.events.insertOne({
    event_name: "Lab Start",
    timestamp: new Date()
})
  1. Creating a specific date:
db.events.insertOne({
    event_name: "Conference",
    date: new Date("2024-06-15T10:30:00Z")
})
  1. Using timestamp in milliseconds:
db.events.insertOne({
    event_name: "Project Deadline",
    timestamp: new Date(1718476800000)
})

Let's verify the inserted documents:

db.events.find()

Example output:

[
  {
    _id: ObjectId("..."),
    event_name: 'Lab Start',
    timestamp: 2024-02-15T12:34:56.789Z
  },
  {
    _id: ObjectId("..."),
    event_name: 'Conference',
    date: 2024-06-15T10:30:00.000Z
  },
  {
    _id: ObjectId("..."),
    event_name: 'Project Deadline',
    timestamp: 2024-06-15T00:00:00.000Z
  }
]

Let's break down the date insertion methods:

  • new Date() creates a timestamp for the current moment
  • new Date("YYYY-MM-DDTHH:mm:ssZ") creates a specific date and time
  • new Date(milliseconds) creates a date from Unix timestamp in milliseconds

Query Date Ranges

In this step, you'll learn how to query date ranges in MongoDB. Building on the previous step, we'll use the datelab database to demonstrate various date range queries.

First, let's ensure we're in the right database and verify our existing documents:

use datelab
db.events.find()

Now, let's add more events to create a more interesting dataset:

db.events.insertMany([
    {
        event_name: "Summer Conference",
        date: new Date("2024-07-15T09:00:00Z")
    },
    {
        event_name: "Winter Workshop",
        date: new Date("2024-01-20T14:30:00Z")
    },
    {
        event_name: "Spring Meetup",
        date: new Date("2024-04-10T11:15:00Z")
    }
])

Let's explore different ways to query date ranges:

  1. Find events after a specific date:
db.events.find({
    date: { $gt: new Date("2024-06-01") }
})
  1. Find events between two dates:
db.events.find({
    date: {
        $gte: new Date("2024-01-01"),
        $lt: new Date("2024-06-01")
    }
})
  1. Using comparison operators with dates:
db.events.find({
    date: {
        $gte: new Date("2024-01-01"),
        $lte: new Date("2024-12-31")
    }
})

Explanation of query operators:

  • $gt: Greater than
  • $gte: Greater than or equal to
  • $lt: Less than
  • $lte: Less than or equal to

Example output:

[
  {
    _id: ObjectId("..."),
    event_name: 'Winter Workshop',
    date: 2024-01-20T14:30:00.000Z
  },
  {
    _id: ObjectId("..."),
    event_name: 'Spring Meetup',
    date: 2024-04-10T11:15:00.000Z
  }
]

Format Date Output

In this step, you'll learn how to format date output in MongoDB using various methods. We'll continue using the datelab database from previous steps.

First, let's ensure we're in the right database:

use datelab

MongoDB provides several ways to format dates. We'll explore different formatting techniques:

  1. Using $dateToString aggregation operator:
db.events.aggregate([
    {
        $project: {
            event_name: 1,
            formatted_date: {
                $dateToString: {
                    format: "%Y-%m-%d %H:%M:%S",
                    date: "$date"
                }
            }
        }
    }
])
  1. Extracting specific date components:
db.events.aggregate([
    {
        $project: {
            event_name: 1,
            year: { $year: "$date" },
            month: { $month: "$date" },
            day: { $dayOfMonth: "$date" },
            hour: { $hour: "$date" }
        }
    }
])
  1. Creating custom date formats:
db.events.aggregate([
    {
        $project: {
            event_name: 1,
            custom_format: {
                $dateToString: {
                    format: "%B %d, %Y at %I:%M %p",
                    date: "$date"
                }
            }
        }
    }
])

Date formatting specifiers:

  • %Y: 4-digit year
  • %m: Month as two-digit number
  • %d: Day of the month
  • %H: Hour (24-hour clock)
  • %I: Hour (12-hour clock)
  • %M: Minutes
  • %S: Seconds
  • %p: AM/PM indicator

Example output:

[
  {
    _id: ObjectId("..."),
    event_name: 'Summer Conference',
    formatted_date: '2024-07-15 09:00:00',
    year: 2024,
    month: 7,
    day: 15,
    hour: 9,
    custom_format: 'July 15, 2024 at 09:00 AM'
  }
]

Update Date Fields

In this step, you'll learn how to update date fields in MongoDB. We'll continue using the datelab database from previous steps and explore various date update techniques.

First, let's ensure we're in the right database:

use datelab

Let's start by adding a few more events to work with:

db.events.insertMany([
    {
        event_name: "Tech Conference",
        date: new Date("2024-08-20T10:00:00Z"),
        status: "Planned"
    },
    {
        event_name: "Developers Meetup",
        date: new Date("2024-09-15T14:30:00Z"),
        status: "Pending"
    }
])

Now, let's explore different ways to update date fields:

  1. Update a single document's date:
db.events.updateOne(
    { event_name: "Tech Conference" },
    {
        $set: {
            date: new Date("2024-09-01T10:00:00Z"),
            status: "Confirmed"
        }
    }
)
  1. Update multiple documents using date operations:
db.events.updateMany(
    { date: { $lt: new Date("2024-07-01") } },
    {
        $set: {
            status: "Historical",
            updated_at: new Date()
        }
    }
)
  1. Increment date using $currentDate:
db.events.updateOne(
    { event_name: "Developers Meetup" },
    {
        $currentDate: {
            last_modified: true
        },
        $inc: {
            "event_duration.days": 1
        }
    }
)

Let's verify our updates:

db.events.find()

Example output:

[
  {
    _id: ObjectId("..."),
    event_name: 'Tech Conference',
    date: 2024-09-01T10:00:00.000Z,
    status: 'Confirmed'
  },
  {
    _id: ObjectId("..."),
    event_name: 'Developers Meetup',
    date: 2024-09-15T14:30:00.000Z,
    status: 'Pending',
    last_modified: ISODate("2024-02-15T12:34:56.789Z")
  }
]

Key update operators:

  • $set: Replace field values
  • $currentDate: Update with current timestamp
  • $inc: Increment numeric values
  • $unset: Remove fields

Sort By Date

In this final step, you'll learn how to sort documents by date in MongoDB. We'll continue using the datelab database from previous steps and explore various sorting techniques.

First, let's ensure we're in the right database:

use datelab

Let's add a few more events to create a diverse dataset:

db.events.insertMany([
    {
        event_name: "AI Summit",
        date: new Date("2024-10-15T09:00:00Z"),
        category: "Technology"
    },
    {
        event_name: "Blockchain Workshop",
        date: new Date("2024-05-22T14:30:00Z"),
        category: "Finance"
    },
    {
        event_name: "Cloud Computing Expo",
        date: new Date("2024-03-10T11:15:00Z"),
        category: "IT"
    }
])

Now, let's explore different ways to sort documents by date:

  1. Sort events in ascending order (earliest to latest):
db.events.find().sort({ date: 1 })
  1. Sort events in descending order (latest to earliest):
db.events.find().sort({ date: -1 })
  1. Combine sorting with filtering:
db.events.find({
    category: "Technology"
}).sort({ date: 1 })
  1. Advanced sorting with multiple criteria:
db.events.find().sort({
    category: 1,  // Sort by category first
    date: -1      // Then by date in descending order
})

Let's verify our sorting results:

db.events.find({}, {
    event_name: 1,
    date: 1,
    category: 1
}).sort({ date: 1 })

Example output:

[
  {
    _id: ObjectId("..."),
    event_name: 'Cloud Computing Expo',
    date: 2024-03-10T11:15:00.000Z,
    category: 'IT'
  },
  {
    _id: ObjectId("..."),
    event_name: 'Blockchain Workshop',
    date: 2024-05-22T14:30:00.000Z,
    category: 'Finance'
  },
  {
    _id: ObjectId("..."),
    event_name: 'AI Summit',
    date: 2024-10-15T09:00:00.000Z,
    category: 'Technology'
  }
]

Sorting key points:

  • 1: Ascending order
  • -1: Descending order
  • Can sort by multiple fields
  • Works with dates, strings, numbers

Summary

In this lab, you learned how to insert date values in MongoDB using various methods, including using the current date, creating a specific date, and using a timestamp in milliseconds. You also explored querying date ranges, formatting date output, updating date fields, and sorting by date. These techniques are essential for working with temporal data in MongoDB applications.

The lab covered key concepts such as creating a database, inserting documents with date fields, querying data based on date ranges, formatting date output, updating date-related fields, and sorting data by date. These skills are fundamental for building applications that require working with dates and timestamps in a MongoDB database.

Other MongoDB Tutorials you may like