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
相关产品推荐
相关产品推荐

