DEV Community

Cover image for MongoDB Marvels - Dancing with Dates - Series #12
Functional Javascript
Functional Javascript

Posted on

2

MongoDB Marvels - Dancing with Dates - Series #12

MongoDB Marvels - Dancing with Dates - Series #12

MongoDB - Working with dates

Intro

If you insert a doc with no explicit PK (primary key) — which is by default a field with a _id key — Mongo will insert an autogenerated value for you.

One useful feature is that embedded in that PK is the ISODate.

We can extract it like this:

  mgArr(dbEnum.nlpdb, collEnum.users_actions,
    { $addFields: { ts: { $toDate: "$_id" } } },
    lastInserted(1),
  )

Enter fullscreen mode Exit fullscreen mode

We get this output:

/*
@output

{
    _id: 60245842f36c37895594ebb0,
    actionCateg: 'fav',
    hw_id: 'distrail__01',
    user_id: '6024574e948c3b4a8cb99d2e',
    hw: 'distrail',
    isFav: true,
    ts: 2021-02-10T22:03:46.000Z
  }
*/
Enter fullscreen mode Exit fullscreen mode

Notes

Let me read in natural English what the query is doing:

Return an array from the mongo collection,

  • but in the first stage of the pipeline, shape the resultset by adding a new field to it called ts (meaning timestamp, which will represent the original insert date of the record).

And the value of the new ts field will be retrieved from the _id field (the PK field).
Notice two things:

  • we use the mongo $toDate operator as a utility function that extracts the date from the _id field. Note the interesting syntax, which is when we want to reference a field key from the value side ({$MONGO_OPERATOR: VALUESIDE}), we prefix the key name with the dollar sign sigil. Since it's on the value side, it must be a string, so it's wrapped in quotes.

So to summarize, we added a field to our result set, whose key is "ts" and whose value is the extracted date from the _id field.

The output resultset has a new field called ts that is not in the document in the db collection. It was calculated on the fly.

This is a short example, but I wanted to explain it fully.

Not related to "dates" — but just to explain — the second stage (and last stage) is my lastInserted utility func which simply retrieves the last inserted doc from the collection.
Here's the source code for it if you're interested:

/*
@param {number} lim - the count of the most recent inserted docs we want
@return {object[]} - an arr of two stages
*/
export const lastInserted = lim => {
  return [
    sortDesc("_id"),
    limit(lim),
  ];
};

Enter fullscreen mode Exit fullscreen mode

What's Next

As the Series continues we'll cover more interesting queries with dates.

For example, We can select sets of docs between dates, like monthly, weekly, daily, or hourly.

We can even create dimensions of time-series reports.

The limit is your imagination. :)

Dynatrace image

Highlights from KubeCon Europe 2025

From platform engineering to groundbreaking advancements in security and AI, discover the KubeCon Europe 2025 insights that are shaping the future of cloud native observability.

Learn more

Top comments (0)

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

👋 Kindness is contagious

Delve into this thought-provoking piece, celebrated by the DEV Community. Coders from every walk are invited to share their insights and strengthen our collective intelligence.

A heartfelt “thank you” can transform someone’s day—leave yours in the comments!

On DEV, knowledge sharing paves our journey and forges strong connections. Found this helpful? A simple thanks to the author means so much.

Get Started