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

如何根据ingredients数组长度筛选Mongoose中符合min、max条件的Recipe文档

解决方案

Mongodb/Mongoose 对数组长度做范围查询有两种常用实现方式,优先推荐第一种:

方法1:使用 $expr + $size 实现(推荐)

这是官方推荐的标准写法,性能优于$where查询,支持索引优化:

// 此处的 min、max 是你传入的数值参数
const result = await Recipe.find({
  $expr: {
    $and: [
      // 数组长度大于 min
      { $gt: [{ $size: "$ingredients" }, min] },
      // 数组长度小于 max
      { $lt: [{ $size: "$ingredients" }, max] }
    ]
  }
});

如果你的查询逻辑需要包含边界值(即长度≥min且≤max),只需要把$gt替换为$gte、$lt替换为$lte即可。

方法2:使用 $where 实现(兼容旧版本)

如果你的MongoDB版本低于3.6不支持$expr,可以用这种写法,缺点是性能较差,不适合高并发场景:

const result = await Recipe.find({
  $where: `this.ingredients.length > ${min} && this.ingredients.length < ${max}`
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:15:00