這是Streak Collection,我想在streaks 陣列中搜索今天的日期(如果它存在)然后簡單地更新問題計數,否則用今天的日期創建一個新物件。
_id : {
type: mongoose.Types.ObjectId,
ref: "User",
},
streaks :[{
date :{
type : Date,
required : true
},
questionCount :{
type : Number,
required : true,
default : 0
}
}]
uj5u.com熱心網友回復:
詢問
- 檢查
$$NOW日期是否是新的 - 如果新
$concatArrays添加新日期counter=1 - 否則
$map只更新找到日期的計數器
*$$NOW是一個具有當前日期的系統變數,如果你不想要當前日期,你可以把你喜歡的任何日期放在“$$NOW”的地方
* $dateTruncwith 只unit=day保留日期前一天的部分(忽略時間)
示例是為 2021 年 11 月 20 日制作的(如果您稍后
測驗,請更改資料)此處測驗代碼(今天存在)
此處測驗代碼(今天不存在)
update(
{"_id": {"$eq": 1}},
[{"$set":
{"new":
{"$eq":
[{"$filter":
{"input": "$streaks",
"cond":
{"$eq":
[{"$dateTrunc": {"date": "$$NOW", "unit": "day"}},
{"$dateTrunc": {"date": "$$this.date", "unit": "day"}}]}}},
[]]}}},
{"$set":
{"streaks":
{"$cond":
["$new",
{"$concatArrays":
["$streaks", [{"date": "$$NOW", "questionCount": 1}]]},
{"$map":
{"input": "$streaks",
"in":
{"$cond":
[{"$eq":
[{"$dateTrunc": {"date": "$$NOW", "unit": "day"}},
{"$dateTrunc": {"date": "$$this.date", "unit": "day"}}]},
{"$mergeObjects":
["$$this",
{"questionCount": {"$add": ["$$this.questionCount", 1]}}]},
"$$this"]}}}]}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/361381.html
