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

MongoDB聚合如何按自定义规则将checkins子数组合并为对象

你可以直接使用以下MongoDB聚合语句实现需求:

db.你的集合名.aggregate([
  {
    $addFields: {
      checkin: {
        $switch: {
          branches: [
            // 空数组返回null
            { case: { $eq: [{ $size: "$checkins" }, 0] }, then: null },
            // 仅1个元素时直接返回该元素
            { case: { $eq: [{ $size: "$checkins" }, 1] }, then: { $first: "$checkins" } }
          ],
          // 多个元素时合并首尾指定属性
          default: {
            _id: { $first: "$checkins._id" },
            in_at: { $first: "$checkins.in_at" },
            out_at: { $last: "$checkins.out_at" }
          }
        }
      }
    }
  },
  // 移除原checkins字段,输出符合要求的结构
  {
    $project: {
      name: 1,
      checkin: 1,
      _id: 0
    }
  }
])

如果你使用的MongoDB版本低于4.4,不支持直接对数组使用$first/$last运算符,可以用$arrayElemAt替换对应逻辑:

  • 替换$first: "$checkins"为{ $arrayElemAt: ["$checkins", 0] }
  • 替换$first: "$checkins.xxx"为{ $arrayElemAt: ["$checkins.xxx", 0] }
  • 替换$last: "$checkins.xxx"为{ $arrayElemAt: ["$checkins.xxx", -1] }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:39:00