請告訴我如何滿足以下條件 - 如果 info.startDate 欄位中的時間不等于 00 小時,則將日期(2021-05-27)提前 1 天,將時間設定為 00:00: 00.000Z。我試圖通過 Mongock 笨拙地完成它,獲取集合的所有元素并通過 LocalDateTime 進行檢查,但是我的堆溢位,這是合乎邏輯的,因為集合很大。我如何通過 Mongock 或至少手動請求 MongoDB 來做到這一點。到目前為止,我只寫了這個:
db.getSiblingDB("ervk_core").getCollection("supervision").updateMany(
{},
[
{
"$set": {
"info.startDate": {
"$cond": {
if: {
$eq: [
"$info.startDate",
(there should be a condition at midnight)
]
},
then: (here the day should be added to full and the time should be set to midnight)
}
}
}
}
])
我想使用 dateToString 按小時進行部分搜索,但據我了解,此功能只能在聚合中使用。
我會很感激你的幫助:)
uj5u.com熱心網友回復:
如果您使用的是 Mongo 5.0 版,那么您可以使用$dateTrunc和$dateAdd很容易地實作這一點,如下所示:
db.collection.updateMany(
{},
[
{
$set: {
"info.startDate": {
$cond: [
{
$ne: [
{
$hour: "$info.startDate"
},
0
]
},
{
$dateTrunc: {
date: {
$dateAdd: {
startDate: "$info.startDate",
unit: "day",
amount: 1
}
},
unit: "day",
}
},
"$info.startDate"
]
}
}
}
])
對于較舊的 Mongo 版本,這有點混亂,您應該使用$dateFromParts創建新的日期物件,如下所示:
db.collection.updateMany(
{},
[
{
$set: {
"info.startDate": {
$cond: [
{
$ne: [
{
$hour: "$info.startDate"
},
0
]
},
{
$dateFromParts: {
"year": {
$year: {
$add: [
"$info.startDate",
86400000
]
}
},
"month": {
$month: {
$add: [
"$info.startDate",
86400000
]
}
},
"day": {
$dayOfMonth: {
$add: [
"$info.startDate",
86400000
]
}
},
"hour": 0,
"minute": 0,
"second": 0,
"millisecond": 0,
}
},
"$info.startDate"
]
}
}
}
])
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/433607.html
