Q:

Modify a field of all documents by appending time in the 'hh: mm A' format

These are the documents I have inside a collection:
[
  {
    "unix_date": 1582133934,
    "text": "mongo"
  },  
  {
    "unix_date": 1580068560,
    "text": "some"
  },
]

I want to change the text field of all documents so that they look this way:
[
  {
    "unix_date": 1582133934,
    "text": "mongo 12:00 PM"
  },  
  {
    "unix_date": 1580068560,
    "text": "some 3:00 PM"
  },
]

Note that I used random times.
This is what I tried:
db.collection.update({}, [{
  $set: {
    text: {
      $concat: ["$text", new Date("$unix_date" * 1000).toString()]
    }
  }
}], {
  multi: true
})

this is appending invalid date to the text field and even if it does append the correct string how can I format it to hh: mm AM/PM. Is this possible without using any external libraries? I want to do this directly inside the shell.

A:

The reason it's failing is cause you can't execute .Js logic in mongo query like that, try as below :
db.collection.update(
  {},
  [
    {
      $set: {
        text: {
          $concat: ["$text", " ", {
            $let: {
              vars: {
                hourMins: { $dateToString: { format: "%H:%M",date: { $toDate: { $multiply: ["$unix_date",1000]}},timezone: "America/Chicago"}},
                hour: { $hour: { date: { $toDate: { $multiply: [ "$unix_date", 1000 ] } }, timezone: "America/Chicago" } } },
              in: { $concat: [ "$$hourMins", " ", { $cond: [ { $lte: [ "$$hour", 12 ]}, "AM", "PM" ] } ] } }
        }]
        }
      }
    }
  ],
  {
    multi: true,
  }
);

Ref : aggregation-pipeline
Test : mongoplayground

