我有一個集合,其中包含具有這種結構的檔案:
{
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 的最后交易的買家 ID)。然后排除前幾個月的(累積)所有者。
$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'
}
}
}
]
我對任何想法/解決方案持開放態度,它也可能是我以外的其他方式。
謝謝。
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/432879.html
上一篇:@BsonCreator建構式無效。預期類java.lang.String,找到介面java.util.List
下一篇:pymongo更新嵌套資料鍵
