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

MongoDB聚合如何拆分嵌套results数组并生成带索引的独立对象

MongoDB聚合实现方案

该需求可以直接通过MongoDB标准聚合管道实现,具体实现思路如下:

  • 第一步:过滤符合条件的文档
    用$match阶段筛选满足规则的文档:要么存在booking字段,要么不存在links字段,直接过滤掉不符合要求的无效数据。
  • 第二步:拆分results数组并生成同组唯一索引
    用$unwind拆分booking.results数组,同时开启includeArrayIndex参数,直接生成同个booking下每个result对应的下标,也就是你需要的同id唯一index字段。
  • 第三步:重构输出字段结构
    用$project把需要的字段提取到文档顶层,丢弃冗余字段,直接输出符合要求的结构。

完整聚合语句参考:

db.collection.aggregate([
  // 过滤符合条件的文档
  {
    $match: {
      $or: [
        { booking: { $exists: true } },
        { links: { $exists: false } }
      ]
    }
  },
  // 拆分results数组,同时生成同组索引
  {
    $unwind: {
      path: "$booking.results",
      includeArrayIndex: "index"
    }
  },
  // 映射输出字段
  {
    $project: {
      _id: 0,
      id: "$booking.id",
      index: 1,
      details: "$booking.details",
      name: "$booking.results.name",
      loggedIn: "$booking.results.loggedIn"
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:36:02