Skip to content Skip to sidebar Skip to footer

Mongodb Shell Script Using Projection To Format Date And Get Local Time

Here is the projection I am using db.MyCollection.aggregate([ { '$match': { 'ProjectID' : 999 } }, { '$sort': { 'CreatedDate': -1 } }, { '$project': {

Solution 1:

You can't directly use "toLocaleString()". However, you can add the offset.

1) Third pipeline is used to add the offset

2) Fourth pipeline is used to format the date

var tzOffset = 5.5 * 1000 * 60 * 60;

db.MyCollection.aggregate( [
   { "$match": { "ProjectID" : 999 } },
   { "$sort": { "CreatedDate": -1 } },
   {          
      $project: {
         localTime: {
            $let: {
               vars: {
                   "localTime": { "$add": [ "$DueDate", tzOffset]

                }
               },
               in: { $add: ["$$localTime"] }
            }
         }
      }
   },
   {          
      $project: {
         "_id": 0, 
         "formattedLocalTime": {
                "$dateToString": { 
                    "format": "%Y-%m-%d %H-%M", 
                    "date": "$localTime"
                }
            }
      }
   }

]);

Input:-

"DueDate" : ISODate("2016-08-11T10:17:09.203Z")
"DueDate" : ISODate("2016-08-11T23:16:09.203Z")

Output:-

"formattedLocalTime":"2016-08-11 15-47""formattedLocalTime":"2016-08-12 04-46"

Please note the output 2. The next date is populated correctly.

Post a Comment for "Mongodb Shell Script Using Projection To Format Date And Get Local Time"