In mongo db have a collection named item where I have 2 fields
I want to create new field where I want to club both date and time ex: itemReceivedDate - 2020-09-21T00:00:00.000+00:00 and itemReceivedTime 1323.
itemReceivedDateAndTime - 2020-09-21T13:23:00.000+00:00
I tried below option
db.item.updateOne({},[
{"$set":{"itemReceivedDateAndTime":{"$toDate":{"$concat":[{"$dateToString":{format:"%Y-%m-%d",date:"$itemReceivedDate"}},"T",{"$toString":"$itemReceivedTime"}]}}}])
Its working fine when I receive time with 4 digits such as 1234 or 2322 But when I get time[int] with 3 or 2 or 1 digit above query will fail.
Any suggestions.
Thanks in advance
I would do it like this:
db.item.updateOne({}, [
{
$set: {
itemReceivedDateAndTime: {
$let: {
vars: {
time: { $concat: ['0000', { $toString: "$ItemReceivedTime" }] },
len: { $strLenCP: { $concat: ['0000', { $toString: "$ItemReceivedTime" }] } }
},
in: {
$dateFromParts: {
year: { $year: "$ItemReceivedDate" },
month: { $month: "$ItemReceivedDate" },
day: { $dayOfMonth: "$ItemReceivedDate" },
hour: { $toInt: { $substrCP: ["$$time", { $subtract: ["$$len", 4] }, 2] } },
minute: { $toInt: { $substrCP: ["$$time", { $subtract: ["$$len", 2] }, 2] } },
timezone: "Europe/Zurich"
}
}
}
}
}
}
])