【问题标题】:Reduce a sub array into an object with a custom formula, MongoDB aggregation使用自定义公式将子数组缩减为对象,MongoDB 聚合
【发布时间】:2021-11-20 17:53:54
【问题描述】:

我正在寻找一种根据自定义要求将元素数组减少为对象的方法。

考虑这样的集合:

[
 { 
   name: "David",
   checkins: [
       {
          _id: "612e162d439cb04934d13f9e",
          in_at: "2021-09-12T08:02:00.000Z",
          out_at: "2021-09-12T09:03:00.000Z"
       },
       {
          _id: "612e162d439cb04934d13f9f",
          in_at: "2021-09-12T10:04:00.000Z",
          out_at: "2021-09-12T11:05:00.000Z"
       },
       {
          _id: "612e162d439cb04934d13f9g",
          in_at: "2021-09-12T12:02:00.000Z",
          out_at: "2021-09-12T14:03:00.000Z"
       }
   ] 
 },
 { 
   name: "Wilson",
   checkins: [
       {
          _id: "612e162d439cb04934d13f9e",
          in_at: "2021-09-12T08:02:00.000Z",
          out_at: "2021-09-12T09:03:00.000Z"
       },
       {
          _id: "612e162d439cb04934d13f9f",
          in_at: "2021-09-12T11:04:00.000Z",
          out_at: "2021-09-12T12:05:00.000Z"
       },
       {
          _id: "612e162d439cb04934d13f9g",
          in_at: "2021-09-12T13:02:00.000Z",
          out_at: "2021-09-12T14:03:00.000Z"
       }
   ]  
 }
]

现在我需要将 checkins 数组减少为单个对象并将其附加到新属性 checkin。只需要合并数组的第一个元素和数组的最后一个元素。如果只有一个元素,只需要使用自己,如果数组为空,则checkin必须为null。输出对象应该是:

{
   _id: 1st_element_id,
   in_at: 1st_element_in_at,
   out_at: last_emenet_out_at
}

所以按照例子,预期的结果是:

[
        {
            name: "David",
            checkin: {
                _id: "612e162d439cb04934d13f9e",
                in_at: "2021-09-12T08:02:00.000Z",
                out_at: "2021-09-12T14:03:00.000Z"
            }
        },
        {
            name: "Wilson",
            checkin: {
                _id: "612e162d439cb04934d13f9e",
                in_at: "2021-09-12T08:02:00.000Z",
                out_at: "2021-09-12T14:03:00.000Z"
            }
        }
]

感谢任何帮助,谢谢!

【问题讨论】:

    标签: mongodb reduce sub-array


    【解决方案1】:
    • $first 获取数组的第一个元素
    • $last 获取数组的最后一个元素
    • $mergeObjects 合并第一个和最后一个 out_at 属性对象
    db.collection.aggregate([
      {
        $addFields: {
          checkin: {
            $mergeObjects: [
              {
                $first: "$checkins"
              },
              {
                out_at: {
                  $last: "$checkins.out_at"
                }
              }
            ]
          }
        }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2020-01-26
      • 2015-11-16
      • 2014-08-19
      • 1970-01-01
      相关资源
      最近更新 更多