[英]MongoDB match if input exists (aggregation)
$match: {
date: { $gte: fromDate, $lte: toDate },
if (userId) {
user: userId
}
},
僅當提交了userId
時,我才嘗試匹配用戶。 做這個的最好方式是什么。
您可以使用mongoose 查詢生成器,根據您的條件管理聚合階段,
// INITIALIZE
let p = YourSchemaModel.aggregate();
// DATE FILTER
p.match({ date: { $gte: fromDate, $lte: toDate } });
// USER ID FILTER
if (userId) p.match({ user: userId });
// RESULT
let result = await p.exec();
如果兩者都在一起,聚合將自動合並
$match
階段!
第二種選擇:
let result = await YourSchemaModel.aggregate().match(
Object.assign(
{ date: { $gte: fromDate, $lte: toDate } },
userId ? { user: userId } : {}
)
).exec();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.