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

如何查询MongoDB中机构名称或代码匹配指定值的文档?

MongoDB 查询满足数组元素匹配或字段匹配的文档

你可以使用 MongoDB 的 $or 操作符结合 $regex 来实现需求,查询语句如下:

db.collection.find({
  $or: [
    // 匹配 code 字段包含目标值(数字转字符串后模糊匹配)
    {
      $expr: {
        $regexMatch: {
          input: { $toString: "$code" },
          regex: req.body.searchValue,
          options: "i" // 可选,忽略大小写
        }
      }
    },
    // 匹配 institutes 数组中任意元素的 name 包含目标值
    { "institutes.name": { $regex: req.body.searchValue, $options: "i" } }
  ]
})

代码说明:

  • $or:将两个查询条件组合,只要满足其中一个条件的文档就会被返回
  • 针对数字类型的 code 字段:通过 $toString 将数字转换为字符串,再用 $regexMatch 聚合表达式实现模糊匹配,以此支持“包含”的查询逻辑
  • 针对 institutes 数组:直接通过路径 "institutes.name" 指定数组内的字段,MongoDB 会自动遍历数组元素,只要存在任意一个元素的 name 匹配正则,该文档就会被选中
  • $options: "i":可选参数,用于忽略大小写匹配,如果不需要可以去掉

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:40:28