我的收藏vacation看起來像這樣:
[
{
_id: ..
employeeId: ...
type: ...
startDate:2022-09-10T00:00:00.000 00:00
endDate: 2022-09-15T00:00:00.000 00:00
}
{
_id: ..
employeeId: ...
type: ...
startDate:2022-01-10T00:00:00.000 00:00
endDate: 2022-02-15T00:00:00.000 00:00
}
{
_id: ..
employeeId: ...
type: ...
startDate:2022-03-10T00:00:00.000 00:00
endDate: 2022-04-15T00:00:00.000 00:00
}
]
...
我只想在月份startDate等于特定月份時獲取檔案
const Vacation = require("../models/Vacation");
const vacations = await Vacation.find({// where month in startDate is equal to 2})
我怎樣才能執行這樣的查詢?提前致謝
uj5u.com熱心網友回復:
您可以像這樣撰寫聚合查詢:
const vacations = await Vacation.aggregate(
[
{
"$match": {
$expr: {
"$eq": [
{
"$month": {
"$dateFromString": {
"dateString": "$startDate",
}
}
},
3
]
}
}
},
]
);
在這里,我們使用$dateFromString運算子從字串構造一個日期物件,然后使用$month. 然后我們執行相等比較,使用$eq. 在此處閱讀有關 MongoDB 上的聚合操作的更多資訊。請參閱上面的查詢在這里作業。
uj5u.com熱心網友回復:
正如我的評論中提到的,您不需要$dateFromString正確存盤日期值:
db.collection.aggregate([
{
"$match": {
$expr: {
"$eq": [{ "$month": "$startDate" }, 3 ]
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/506429.html
下一篇:貓鼬模型變數沒有設定型別
