我正在嘗試獲取在特定月份之前注冊的用戶:
const getUsersWhoRegisteredBeforeAGivenMonth = async (month, year) => {
const project_stage = {
$project: {
year: { $year: "$date" },
month: { $month: "$date" },
},
};
const filter_stage = {
$match: {
year: {
$lte: parseInt(year),
},
month: {
$lte: parseInt(month),
},
},
};
const pipeline = [project_stage, filter_stage];
const users = await User.aggregate(pipeline);
return users;
};
但是,這會回傳錯誤的結果。
當month = 1和時,它不會回傳01/2022year = 2022之前創建的所有檔案,而是回傳從2022 年初到01/2022年底創建的檔案以及從2021 年初到01/2021年底創建的檔案。
如果我選擇02/2022,它會做同樣的事情,直到02/2022和01/2021結束。
知道如何解決這個問題嗎?
uj5u.com熱心網友回復:
建議使用$dateFromParts來比較您的方案的日期。
db.collection.aggregate([
{
$match: {
$expr: {
$lt: [
"$date",
{
"$dateFromParts": {
"year": 2022,
"month": 2
}
}
]
}
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470249.html
