【问题标题】:Last value by type with _id relation具有 _id 关系的类型的最后一个值
【发布时间】:2021-03-22 23:36:01
【问题描述】:

我有一个包含 type 的事件集合,可以是 012345createdAt 日期。每个事件都与另一个称为 RTS 的集合相关。

我想为每个 Rts 收集每个类型的最后一个事件。

使用我的解决方案时遇到问题:

问题是,我必须一一描述每个types 才能使其正常工作。是否有任何解决方案可以通过type 值诱导动态密钥创建?

这是我现在得到的:

  1. 我对数据进行排序
  2. idRTS 分组,其中包含指向第二个集合的链接。对于每种类型,将值推送到特定数组中。
  3. 从类型数组中删除空值。
  4. 只保留第一个值(the most updated)
  5. 使数据可呈现。

[
  {
    $sort: {
      idRTS: -1,
      createdAt: -1
    }
  },
  {
    $group: {
      _id: '$idRTS',
      type0: {
        $push: {
          $cond: {
            if: {
              $eq: [
                '$type', 0
              ]
            },
            then: '$$ROOT',
            else: null
          }
        }
      },
      type5: {
        $push: {
          $cond: {
            if: {
              $eq: [
                '$type', 5
              ]
            },
            then: '$$ROOT',
            else: null
          }
        }
      }
    }
  },
  {
    $project: {
      _id: '$_id',
      type0: {
        '$filter': {
          'input': '$type0',
          'as': 'd',
          'cond': {
            '$ne': [
              '$$d', null
            ]
          }
        }
      },
      type5: {
        $filter: {
          input: '$type5',
          as: 'd',
          cond: {
            $ne: [
              '$$d', null
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      _id: '$_id',
      type0: {
        $arrayElemAt: [
          '$type0', 0
        ]
      },
      type5: {
        '$arrayElemAt': [
          '$type5', 0
        ]
      }
    }
  }
]

【问题讨论】:

    标签: node.js mongodb mongoose aggregate


    【解决方案1】:
    • $match 输入 0 或 5
    • $sort idRTScreatedAt 按降序排列
    • $group idRTScreatedAt 字段并获取第一个对象,这将获得两种类型的第一个文档
    • $group by idRTS 并以 k(key) 和 v(value) 格式制作两种类型的数组
    • $project 使用 $objectToArraytype 数组转换为对象
    db.collection.aggregate([
      { $match: { type: { $in: [0, 5] } } },
      {
        $sort: {
          idRTS: -1,
          createdAt: -1
        }
      },
      {
        $group: {
          _id: {
            idRTS: "$idRTS",
            type: "$type"
          },
          type: { $first: "$$ROOT" }
        }
      },
      {
        $group: {
          _id: "$_id.idRTS",
          type: {
            $push: {
              k: { $toString: "$type.type" },
              v: "$type"
            }
          }
        }
      },
      { $project: { type: { $arrayToObject: "$type" } } }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2023-03-12
      • 2015-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多