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

如何在MongoDB中约束查询:筛选特定条件文档并修剪返回条目

MongoDB 查询方案:匹配并保留指定条件的嵌套条目

针对你的需求,我们可以通过MongoDB聚合管道实现以下目标:筛选出同时包含fieldA为"aaa"和"eee"的条目,且这两个条目的fieldB值完全匹配的文档,同时仅保留符合条件的条目而非完整文档。

完整聚合查询代码

db.collection.aggregate([
  // 第一步:计算当前文档中aaa和eee条目共有的fieldB值
  {
    $addFields: {
      commonBValues: {
        $setIntersection: [
          // 提取所有fieldA为"aaa"的entry的fieldB值
          {
            $map: {
              input: {
                $filter: {
                  input: "$data",
                  cond: { $eq: ["$$this.entry.fieldA", "aaa"] }
                }
              },
              as: "item",
              in: "$$item.entry.fieldB"
            }
          },
          // 提取所有fieldA为"eee"的entry的fieldB值
          {
            $map: {
              input: {
                $filter: {
                  input: "$data",
                  cond: { $eq: ["$$this.entry.fieldA", "eee"] }
                }
              },
              as: "item",
              in: "$$item.entry.fieldB"
            }
          }
        ]
      }
    }
  },
  // 第二步:筛选出存在共有fieldB值的文档(即符合条件的文档)
  {
    $match: {
      $expr: { $ne: ["$commonBValues", []] }
    }
  },
  // 第三步:过滤出仅包含符合条件的entry
  {
    $project: {
      _id: 0, // 可选:不需要返回_id则保留此配置
      matchedEntries: {
        $filter: {
          input: "$data",
          cond: {
            $and: [
              // 只保留fieldA为aaa或eee的entry
              { $in: ["$$this.entry.fieldA", ["aaa", "eee"]] },
              // 只保留fieldB在共有值列表中的entry
              { $in: ["$$this.entry.fieldB", "$commonBValues"] }
            ]
          }
        }
      }
    }
  },
  // 可选:清理中间生成的commonBValues字段
  { $unset: "commonBValues" }
])

各阶段说明

  1. $addFields:新增commonBValues字段,计算当前文档中fieldA为"aaa"和"eee"的条目之间,fieldB的共有值。如果共有值为空,说明该文档不符合条件。
  2. $match:仅保留commonBValues不为空的文档,也就是存在匹配的aaa和eee条目的文档。
  3. $project:生成最终结果,用$filter遍历data数组,只保留同时满足fieldA是"aaa"/"eee"、且fieldB在共有值列表中的条目,同时可以选择去掉默认的_id字段。
  4. $unset(可选):移除中间生成的commonBValues字段,让结果更简洁。

结果示例

针对你提供的doc1,查询返回的结果为:

{
  "matchedEntries": [
    {
      "entry": { "fieldA": "aaa", "fieldB": "xxx" }
    },
    {
      "entry": { "fieldA": "eee", "fieldB": "xxx" }
    }
  ]
}

而doc2和docN因不符合条件,不会出现在结果中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:55:23