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

MongoDB查询含数字9的字段问题求助(数组与字符串型数字场景)

MongoDB 查询包含数字“9”的字段解决方案

针对你提供的文档结构,以下是不同场景下的查询实现:

1. 针对特定字段的精准查询

数组字符串字段(如mobile_no.、customer_name)

MongoDB 对数组字段使用$regex时,会自动匹配数组中任意符合条件的元素,直接写正则即可:

// 匹配 mobile_no. 数组中任意元素含"9"的文档
db.collection.find({
  "mobile_no.": /9/
})

// 匹配 customer_name 数组中任意元素含"9"的文档(语法通用)
db.collection.find({
  "customer_name": /9/
})

字符串形式的数字字段(如customer_age)

customer_age是NumberLong类型,需先转为字符串再做正则匹配,用$expr结合$toString和$regexMatch实现:

// 匹配 customer_age 转字符串后含"9"的文档
db.collection.find({
  $expr: {
    $regexMatch: {
      input: { $toString: "$customer_age" },
      regex: /9/
    }
  }
})

2. 匹配文档中任意字段含"9"的情况

如果需要一次性筛选出**所有字段(包括数组元素、字符串数字、ObjectId)**含"9"的文档,用$or组合多个条件:

db.collection.find({
  $or: [
    // 字符串/数组字符串字段匹配
    { "mobile_no.": /9/ },
    { "customer_name": /9/ },
    // 字符串形式数字字段匹配
    { $expr: { $regexMatch: { input: { $toString: "$customer_age" }, regex: /9/ } } },
    // ObjectId 转字符串后匹配(可选)
    { $expr: { $regexMatch: { input: { $toString: "$_id" }, regex: /9/ } } },
    { $expr: { $regexMatch: { input: { $toString: "$customer_id" }, regex: /9/ } } }
  ]
})

3. 找出文档中具体哪些字段含"9"(带投影结果)

如果需要筛选文档的同时,返回每个文档中符合条件的字段列表,用聚合管道实现:

db.collection.aggregate([
  // 先筛选符合条件的文档
  {
    $match: {
      $or: [
        { "mobile_no.": /9/ },
        { "customer_name": /9/ },
        { $expr: { $regexMatch: { input: { $toString: "$customer_age" }, regex: /9/ } } },
        { $expr: { $regexMatch: { input: { $toString: "$_id" }, regex: /9/ } } },
        { $expr: { $regexMatch: { input: { $toString: "$customer_id" }, regex: /9/ } } }
      ]
    }
  },
  // 投影出含"9"的字段列表
  {
    $project: {
      fields_with_9: {
        $filter: {
          input: { $objectToArray: "$$ROOT" },
          as: "field",
          cond: {
            $or: [
              // 处理普通字段(转字符串后匹配)
              { $regexMatch: { input: { $toString: "$$field.v" }, regex: /9/ } },
              // 处理数组字段(数组中存在元素匹配)
              {
                $and: [
                  { $isArray: "$$field.v" },
                  { $gt: [
                    { $size: { $filter: {
                      input: "$$field.v",
                      as: "elem",
                      cond: { $regexMatch: { input: { $toString: "$$elem" }, regex: /9/ } }
                    } } },
                    0
                  ] }
                ]
              }
            ]
          }
        }
      },
      // 可选:保留原文档内容
      original_doc: "$$ROOT"
    }
  }
])

注意事项

  • 嵌套字段需调整$objectToArray的层级,当前代码适用于你提供的扁平文档结构;
  • $regex默认大小写敏感,若需不区分可使用/9/i(本次仅匹配数字9,无需设置)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:40:38