Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the creation date of _id and add it as a new field using the aggregation framework?

Tags:

mongodb

I have been trying for a while to extract the insertion date of a mongodb document and add it as a new field to the same document.

I'm trying to do it using the mongo and mongo shell aggregation framework without getting good results.

Here is my query

db.getCollection('my_collection').aggregate(
   [    
      {
         $match: {
            MY QUERY CRITERIA
          }
      },
      { 
         $addFields: { "insertTime": "$_id.getTimestamp()" } 
      }
   ]
)

I am trying to extracr insertion time from _id using the function getTimestamp() but for sure there is somtehing about aggregation framework syntax that I am missing because I can not do what I am trying to do in my query.

This works perfect:

ObjectId("5c34f746ccb26800019edd53").getTimestamp()

ISODate("2019-01-08T19:17:26Z")

But this does not work at all:

"$_id.getTimestamp()"

What I am missing?

Thanks in advance

like image 266
Hal Avatar asked Sep 14 '25 17:09

Hal


1 Answers

Simply use the $addFields with "$_id":

{
    $addFields: {
        date: {"$toDate": "$_id"}
    }
}
like image 54
zamoosh Avatar answered Sep 16 '25 08:09

zamoosh