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

如何在MongoDB中识别双数组配置并标记类型返回指定数组

MongoDB 合并配置数组并标记类型

可以通过MongoDB聚合管道实现需求,以下是完整的聚合查询:

db.collection.aggregate([
  // 为两个数组的元素添加初始type字段并合并为临时数组
  {
    $project: {
      tempConfigs: {
        $concatArrays: [
          { $map: { input: "$directConfigs", as: "dc", in: { id: "$$dc.id", name: "$$dc.name", type: "direct" } } },
          { $map: { input: "$indirectConfigs", as: "ic", in: { id: "$$ic.id", name: "$$ic.name", type: "indirect" } } }
        ]
      }
    }
  },
  // 拆分临时数组并按id分组,收集类型信息
  { $unwind: "$tempConfigs" },
  {
    $group: {
      _id: "$tempConfigs.id",
      name: { $first: "$tempConfigs.name" },
      types: { $addToSet: "$tempConfigs.type" }
    }
  },
  // 根据类型集合判断最终type值
  {
    $project: {
      _id: 0,
      id: "$_id",
      name: 1,
      type: {
        $cond: {
          if: { $eq: [ { $size: "$types" }, 2 ] },
          then: "Both",
          else: { $arrayElemAt: [ "$types", 0 ] }
        }
      }
    }
  },
  // 整理为目标格式的configs数组
  {
    $group: {
      _id: null,
      configs: { $push: "$$ROOT" }
    }
  },
  { $project: { _id: 0, configs: 1 } }
])

逻辑说明:

  1. 标记初始类型并合并:用$map给两个数组的元素分别打上direct/indirect类型标签,再通过$concatArrays合并成临时数组。
  2. 分组聚合类型:拆分临时数组后按id分组,收集每个配置对应的所有类型(自动去重),同时保留配置名称。
  3. 确定最终类型:判断类型集合的长度,长度为2说明配置同时存在于两个数组,标记为Both;否则保留唯一的类型标签。
  4. 格式化输出:将所有配置重新组合成目标结构的configs数组,移除无关字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:50:38