我有以下架構。
const dish = new Schema({
name: {
type: string,
},
createdAt: {
type: Date,
},
)
我想獲取昨天中午 12 點到今天中午 12 點之間創建的菜肴。
uj5u.com熱心網友回復:
const dish = await Dish.aggregate([
{
$match: {
$and: [
{ createdAt: { $lt: new Date(new Date().setHours(0, 0, 0))}},
{ createdAt: { $gte: new Date(new Date().setHours(0, 0, 0) - 24 * 60 * 60 * 1000)}}
]
}
}
]);
編輯:這是解釋。
new Date()給你一個日期,2022-11-15T22:14:00.000 00:00但new Date().setHours(0,0,0)會將值設定為凌晨 12 點,但也會給你以毫秒為單位的值1668449700000。
您的 createdAt 的日期值類似于2022-11-15T22:14:00.000 00:00。使用{ $lt: new Date().setHours(0, 0, 0)}}它將嘗試比較日期和整數[ 2022-11-15T22:14:00.000 00:00, 1668449700000] 之間的值,因此您將得到錯誤的結果。
因此,您需要將其放入 new Date() 以獲取 Date 中的值,以便$lt可以正確比較。new Date(new Date().setHours(0, 0, 0))}將等于new Date(1668449700000)它會給你一個日期值,并且$lt也會正常作業。
至于第二個條件,24 * 60 * 60 * 1000是以毫秒為單位的1天。所以我減去它以獲得昨天凌晨 12 點的毫秒數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534207.html
標籤:数据库猫鼬
下一篇:聚合函式Mongoose-節點
