You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:15:35