如何按月计算新值?

How to get count of new values by months?

我有一个集合,其中包含具有以下结构的文档:

{
    car: carId,
    seller: sellerId,
    buyer: buyerId,
    timestamp: timestamp
}

我想按月提取独特的新(第一次拥有汽车)车主数量。

所以预期结果如下:

[
    {
        date: 2022-01-01T00:00:00.000+00:00,
        newCarOwners: 28
    },
    {
        date: 2022-02-01T00:00:00.000+00:00,
        newCarOwners: 18
    },
    {
        date: 2022-03-01T00:00:00.000+00:00,
        newCarOwners: 10
    }
    ...
]

我想我可以通过按月份和 carId 对文档进行分组,然后按月份查找所有者(每个 carId 的最后一笔交易的 buyerId)来实现。然后排除前几个月的(累计)所有者。

$setWindowFields 可能有用,但我找不到排除前几个月所有者的方法。

现在我的管道是这样的:

[
    {
        $set: {
            month: {
                $dateTrunc: {
                    date: {
                        $toDate: '$timestamp'
                    },
                    unit: 'month',
                    binSize: 1,
                    timezone: 'GMT',
                }
            }
        }
    }, {
        $group: {
            _id: {
                month: '$month',
                carId: '$carId'
            },
            doc: {
                $max: {
                    ts: '$timestamp',
                    buyer: '$buyer'
                }
            }
        }
    }, {
        $group: {
            _id: {
                month: '$_id.month'
            },
            owners: {
                $addToSet: '$doc.buyer'
            }
        }
    }
]

我对任何 idea/solution 都持开放态度,也可能是其他方式。

谢谢。

db.collection.aggregate([
  {
    $group: {
      _id: "$buyer",
      firstTime: {
        $min: "$timestamp"
      },
      count: { $sum: 1 }
    }
  },
  {
    $match: { count: 1 }
  },
  {
    $group: {
      _id: {
        $dateTrunc: {
          date: { $toDate: "$firstTime" },
          unit: "month",
          binSize: 1,
          timezone: "GMT"
        }
      },
      newCarOwners: { $sum: 1 }
    }
  }
])

mongoplayground