我有以下檔案:
{
timestamp: 2022-11-04T08:58:03.303 00:00
name: Brian
username: B2022@mail.com
type: Type A
}
{
timestamp: 2022-11-04T09:20:13.564 00:00
name: Brian
username: B2022@mail.com
type: Type A
}
{
timestamp: 2022-11-04T13:12:25.024 00:00
name: Anna
username: Anna@something.com
type: Type A
}
{
timestamp: 2022-11-04T05:32:58.834 00:00
name: Max
username: Max@somethingelse.com
type: Type B
}
{
timestamp: 2022-11-04T03:34:23.011 00:00
name: Jan
username: Jan@somethingelse.com
type: Type c
}
我將在時間線圖表中使用這些資料,所以我使用$deinsifyand$fill來創建以周為單位的存盤桶。
現在我正在嘗試將這些資料分組為一周的單位,我這樣做是這樣的:
{
$group: {
_id: {
bins: {
$dateTrunc: {
date: '$timestamp',
unit: 'week',
binSize: 1,
timezone: 'Europe/Paris',
startOfWeek: 'monday'
}
}
}
}
}
這很好用,但是在這個組中,我還想計算型別 A 和 B 的不同用戶名的數量,并且我還想計算型別專門為“型別 A”的檔案的數量。
目標是得到這樣的東西:
{
timestamp: 2022-10-30T23:00:00.000 00:00
usernameCount: 3
typeAOccurencies: 3
}
這是我嘗試過的:
我找不到直接在該組中進行不同計數的方法,所以我認為一種方法是將值添加到陣列中,然后在專案聚合中使用$size,如下所示:
{
$match: {
'logType': {
$in: [ 'Type A', 'Type B' ]
}
}
},
{
$group: {
_id: {
bins: {
$dateTrunc: {
date: '$timestamp',
unit: 'week',
binSize: 1,
timezone: 'Europe/Paris',
startOfWeek: 'monday'
}
}
},
usernameCount: {
$addToSet: '$username'
},
typeAOccurencies: {
$push: '$type'
},
}
},
{
$project: {
_id: 0,
timestamp: '$_id.bins'
usernameCount: {
$size: '$usernameCount'
},
typeAOccurencies: {
$size: '$typeAOccurencies'
}
}
}
我現在唯一的問題是我不知道如何只將具有“Type A”值的型別欄位推送到 typeAOccurencies。現在 Type B 也被推了,它不應該..
uj5u.com熱心網友回復:
更新:使用$sumwith $cond。
db.collection.aggregate([
{
$group: {
_id: {
bins: {
$dateTrunc: {
date: "$timestamp",
unit: "week",
binSize: 1,
timezone: "Europe/Paris",
startOfWeek: "monday"
}
}
},
usernameCount: {
$addToSet: "$username"
},
typeAOccurencies: {
$sum: {
$cond: {
if: {
$eq: [
"$type",
"Type A"
]
},
then: 1,
else: 0
}
}
},
typeBOccurencies: {
$sum: {
$cond: {
if: {
$eq: [
"$type",
"Type B"
]
},
then: 1,
else: 0
}
}
}
}
},
{
$project: {
_id: 0,
timestamp: "$_id.bins",
usernameCount: {
$size: "$usernameCount"
},
typeAOccurencies: 1,
typeBOccurencies: 1
}
}
])
演示@Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/530421.html
