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

ElasticSearch筛选:排除同id多stage文档,保留单stage文档

仅保留单stage条目的文档查询

针对你的文档数据,要排除对应多个stage值的id(比如id=a),只保留仅存在单个stage条目的文档,可通过以下两种方式实现:

方式一:聚合管道一次性查询

直接用聚合管道完成分组统计、筛选和关联,适合直接执行查询:

db.collection.aggregate([
  // 按id分组,统计每个id的stage条目数,记录所有关联的stage值
  {
    $group: {
      _id: "$id",
      stageCount: { $sum: 1 },
      stages: { $addToSet: "$stage" }
    }
  },
  // 筛选出仅含单个stage的分组,若需要限定stage=1,就加上stages:1的条件
  {
    $match: {
      stageCount: 1,
      stages: 1 // 可选条件,不需要的话可删除
    }
  },
  // 关联回原集合获取完整文档
  {
    $lookup: {
      from: "collection", // 替换成你的实际集合名称
      localField: "_id",
      foreignField: "id",
      as: "matchedDocs"
    }
  },
  // 展开文档数组
  { $unwind: "$matchedDocs" },
  // 输出需要的字段(可根据需求调整)
  {
    $project: {
      _id: "$matchedDocs._id",
      id: "$matchedDocs.id",
      stage: "$matchedDocs.stage"
    }
  }
])

方式二:先获取重复id再排除

先找出对应多个stage的id列表,再用这个列表排除文档,适合需要复用重复id的场景:

// 第一步:获取所有对应多个stage的id
var duplicateIds = db.collection.aggregate([
  { $group: { _id: "$id", entryCount: { $sum: 1 } } },
  { $match: { entryCount: { $gt: 1 } } },
  { $project: { _id: 1 } }
]).map(item => item._id);

// 第二步:查询排除重复id的文档,可选加上stage=1的条件
db.collection.find({
  id: { $nin: duplicateIds },
  stage: 1 // 可选条件,不需要可删除
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:32:37