提问者:小点点

带有_id关系的类型的最后一个值


我有一个事件集合,它包含一个类型,可以是012345和一个创建日期。每个事件都与另一个名为RTS的集合相关。

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

使用我的解决方案时出现问题:

问题是,我必须逐一描述每个类型,以便使其工作。是否有任何解决方案可以通过type值进行动态密钥创建?

下面是我现在得到的结果:

  1. 我对数据进行排序
  2. idrts分组,其中包含指向第二个集合的链接。对于每个类型,将值推入特定数组。
  3. 从类型数组中删除空值。
  4. 仅保留第一个值(最新的)
  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
        ]
      }
    }
  }
]

共1个答案

匿名用户

  • $match键入0或5
  • $sortIDRTScreatedat降序
  • $groupidrtscreatedat字段和获取第一个对象,这将获取两种类型的第一个文档
  • $groupIDRTS创建,并以k(键)和v(值)格式创建两种类型的数组
  • $project使用$ObjectToArray
  • Type数组转换为对象
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" } } }
])

操场