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

MongoDB 3.2内嵌对象数组过滤失效问题求助

解决MongoDB 3.2中内嵌数组过滤无效的问题

我来帮你排查下问题所在,以及给出适配MongoDB 3.2的解决方案:

你的聚合语句存在两个关键问题

  1. Input路径错误
    你在$filter里写的input: "$instructions.items"是错误的——因为instructions本身是一个数组,这个写法会把所有instructions元素的items数组合并成一个大数组来过滤,而不是针对每个instructions元素内部的items数组单独处理。

  2. Cond表达式不完整
    你直接在cond里写{ "$regex": "two", "$options": "i" },但没有指定要匹配的目标字段(也就是item.info.text),而且MongoDB 3.2中$regex在聚合表达式里需要明确关联输入字段,不能单独使用。

适配MongoDB 3.2的正确聚合语句

我们需要先用$map遍历外层的instructions数组,再在每个元素内部用$filter处理items数组,确保过滤逻辑作用在正确的层级上:

db.onlineBallots.aggregate([
  // 先匹配目标文档,这一步是对的
  { "$match": { "_id": "112233", "mainOptions.option0": "op0" } },
  {
    "$project": {
      "mainOptions": 1,
      "instructions": {
        "$map": {
          "input": "$instructions",
          "as": "inst",
          "in": {
            // 保留instructions元素的原有字段
            "number": "$$inst.number",
            "header": "$$inst.header",
            // 对当前instructions元素的items数组进行过滤
            "items": {
              "$filter": {
                "input": "$$inst.items",
                "as": "item",
                "cond": {
                  // MongoDB 3.2的$regex表达式写法:[输入字符串, 匹配模式, 选项]
                  "$regex": [ "$$item.info.text", "two", "i" ]
                }
              }
            }
          }
        }
      }
    }
  }
]);

额外说明

如果你的需求是精确匹配"two info"而不是模糊匹配,把cond换成$eq会更高效:

"cond": { "$eq": [ "$$item.info.text", "two info" ] }

这样执行后,返回的文档会保留完整结构,且每个instructions元素的items数组只会包含info.text符合条件的元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:25:34