mongodb - 仅当存在时才匹配 mongodb 查询的变量
问题描述
我正在使用聚合来返回符合特定条件的用户列表。问题是我从前端得到的变量并不总是设置好的。
所以我必须做这样的事情:
const match = {};
if (status) {
match.status = status;
}
if (startDate && endDate) {
match.createdAt = { $gte: startOfDay(startDate), $lte: endOfDay(endDate) };
}
await User.aggregate([
{
$match: match,
},
]);
有没有办法直接在查询中编写它而不必match
在聚合之外使用变量?
解决方案
您可以尝试以下方法:
db.User.find(
{ $or:
[ { $and: [ { "status": { $exists: true } },{ "status": status } ] },
{ $and: [ { "endDate": { $exists: true } },
{ "startDate": { $exists: true } },
{ $gte: startOfDay(startDate), $lte: endOfDay(endDate) }] }
] })
推荐阅读
- objective-c - 未找到合适的应用程序记录,请验证您的 BundleID 是否正确
- azure - 如何使用一个 SSL 证书保护多个 Azure Web 应用程序
- javascript - 如何查找“拒绝执行内联事件处理程序因为违反 CSP blabla”的来源
- excel - 将包含日期的单元格值更改为日期格式后显示的文本
- javascript - 使用 Strapi 获取所有单一类型页面的 GraphQL 查询
- c++ - C++ 向量插入和迭代器混淆
- c++ - 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- android - Android Studio 4 在线版
- c - 在 Mac 终端中打开 C 程序
- excel - 即使数据相同,使用 .value 比较 excel 单元格也不匹配