MongoDB聚合$match中$and与$expr使用问题求助
MongoDB查询$match报错"unknown operator: $and"的解决方法
问题原因
你的代码中,当status为progress或confirmed时,构造的查询条件格式不符合MongoDB规则:
- 直接在
status对象内使用$and时,内部的$ne、$lt等操作符没有明确关联字段; - 尝试
$expr时,表达式的参数格式错误(缺少字段引用的数组结构)。
解决方案
下面提供两种可行的修正方式:
方式一:直接构造多条件查询(推荐)
利用MongoDB同一字段下多操作符默认逻辑与的特性,无需显式使用$and:
const getBookingStatus = (status) => { if (!status) return {}; const qStatus = {}; if (status === 'progress') { qStatus.$ne = statusList.declined; qStatus.$lt = statusList.confirmed; } if (status === 'confirmed') { qStatus.$gt = statusList.signed; qStatus.$lt = statusList.completed; } if (status === 'done') { qStatus.$gte = statusList.completed; } return { status: qStatus }; };
此方式生成的查询结构为{ status: { $ne: xxx, $lt: xxx } },完全符合MongoDB的查询语法规则。
方式二:正确使用$expr聚合表达式
如果需要用$expr,必须在表达式中通过$字段名引用字段,且比较操作符采用数组参数格式:
const getBookingStatus = (status) => { if (!status) return {}; if (status === 'progress') { return { $expr: { $and: [ { $ne: ['$status', statusList.declined] }, { $lt: ['$status', statusList.confirmed] } ] } }; } if (status === 'confirmed') { return { $expr: { $and: [ { $gt: ['$status', statusList.signed] }, { $lt: ['$status', statusList.completed] } ] } }; } if (status === 'done') { return { status: { $gte: statusList.completed } }; } return {}; };
内容的提问来源于stack exchange,提问作者Kevin Ganem
相关产品推荐
相关产品推荐

