在 mongo db 中有一個名為 item 的集合,其中我有 2 個欄位
- ItemReceivedDate - 型別:日期,例如:值/資料 2020-09-21T00:00:00.000 00:00
- ItemReceivedTime - 型別:Int。這是 24 小時格式,
例如: 1. 值為 345 它是凌晨 3:45
2. 值為 1323 -> 1:23 PM
3. 值為 1 -> 12:01 AM
我想創建一個新欄位,我想在其中包含日期和時間,例如:itemReceivedDate - 2020-09-21T00:00:00.000 00:00 和 itemReceivedTime 1323。
itemReceivedDateAndTime - 2020-09-21T13:23:00.000 00:00
我嘗試了以下選項
db.item.updateOne({},[
{"$set":{"itemReceivedDateAndTime":{"$toDate":{"$concat":[{"$dateToString":{format:"%Y-%m-%d",date:"$itemReceivedDate"}},"T",{"$toString":"$itemReceivedTime"}]}}}])
當我收到 4 位數字的時間(例如 1234 或 2322)時,它作業正常但是當我得到 3 位或 2 位或 1 位以上的時間 [int] 時,查詢將失敗。
有什么建議。
提前致謝
uj5u.com熱心網友回復:
我會這樣做:
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"
}
}
}
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414715.html
標籤:
上一篇:嵌套物件查詢mongoDB
