DEV Community

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

Posted on

MongoDB Marvels - Dancing with Dates - Series #12

MongoDB Marvels - Dancing with Dates - Series #12

MongoDB - Working with dates


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" } } },

Enter fullscreen mode Exit fullscreen mode

We get this 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


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 [

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

Top comments (0)