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

如何在MongoDB的$lte操作符中添加条件过滤?

Mongoose 查询过滤逻辑问题

集合模型定义

@Prop({ type: Number, required: true, default: 0 })
have: number;
@Prop({ type: Boolean, required: false, default: null })
unstable?: boolean;
@Prop({ type: Number, required: false, default: null })
max?: number;

过滤规则

  • 若unstable为true则排除该记录;为false或null时忽略此条件
  • 当max不为null时,必须满足have < max;max为null时忽略此条件
  • 两个条件需同时满足,不满足任一则排除

尝试过的无效查询

{
  $and:[
    {
      unstable: {
        $ne: true
      },
    },
    {
      have: {
        $lte: {
          cond: { // 试过$cond,无报错但无结果
            if: {
              max: { $eq: null },
            },
            then: Infinity,
            else: '$max', // 试过Infinity,同样无结果
          },
        },
      },
    },
  ],
}

逻辑意图是实现:

have <= (max === null ? Infinity : max)

单独测试have: { $lte: Infinity }有效,但结合条件后无法得到正确结果。

数据示例

[
  {
    id: 1,
    max: 10,
    have: 1,
    unstable: null,
  },
  {
    id: 2,
    max: 10,
    have: 10,
    unstable: null,
  },
  {
    id: 3,
    max: null,
    have: 1,
    unstable: null,
  },
  {
    id: 4,
    max: null,
    have: 1,
    unstable: true,
  },
]

预期输出

仅返回id:1和id:3:

  • id:2排除:have等于max,不满足have < max
  • id:4排除:unstable为true

正确解决方案

问题出在直接在常规查询条件中使用聚合表达式$cond,MongoDB的普通查询操作符不支持这种嵌套逻辑,需要用$expr包裹聚合判断逻辑。正确查询语句如下:

{
  $and: [
    { unstable: { $ne: true } },
    {
      $expr: {
        $or: [
          { $eq: ["$max", null] },
          { $lt: ["$have", "$max"] }
        ]
      }
    }
  ]
}

逻辑说明

  • 第一个条件直接排除unstable为true的记录
  • 第二个条件通过$expr执行聚合判断:
    • 要么max为null,直接满足条件
    • 要么max不为null,且have小于max

此查询可精准匹配过滤规则,得到预期结果。

内容的提问来源于stack exchange,提问作者Roman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:32:32