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. :)

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

Top comments (0)

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay