我的 MongoDB 中有以下檔案:
_id: ObjectId(...)
'timestamp': 2022-11-03T10:00:00.000 00:00
score: 1
_id: ObjectId(...)
'timestamp': 2022-11-03T09:00:00.000 00:00
score: 3
_id: ObjectId(...)
'timestamp': 2022-11-03T10:00:00.000 00:00
score: 6
_id: ObjectId(...)
'timestamp': 2022-11-03T10:00:00.000 00:00
score: 10
我想做一個聚合,將 (gte)1-(lt)5 范圍內的分數計算為差,(gte)5-(lt)7 為 ok,(gte)7-(lt)8.5 為好, (gte)8.5-(lte)10 一樣優秀。
所以結果看起來像這樣:
{
"data": [
{
"name": "excellent",
"count": 1
},
{
"name": "good",
"count": 0
},
{
"name": "ok",
"count": 1
},
{
"name": "poor",
"count": 2
}
]
}
我該如何做到這一點?
uj5u.com熱心網友回復:
如果您只接受具有計數的檔案的答案,您可以執行以下操作:
db.collection.aggregate([
{$project: {
_id: {
$arrayElemAt: [
["poor", "ok", "good", "excellent"],
{$floor: {$divide: ["$score", 10]}}
]}
}},
{$group: {_id: "$_id", count: {$sum: 1}}}
])
否則,您需要創建所有類別:
db.collection.aggregate([
{$group: {
_id: 0,
excellent: {$sum: {$cond: [{$gte: ["$score", 30]}, 1, 0]}},
good: {$sum: {$cond: [{$and: [{$gte: ["$score", 20]}, {$lt: ["$score", 30]}]}, 1, 0]}},
ok: {$sum: {$cond: [{$and: [{$gte: ["$score", 10]}, {$lt: ["$score", 20]}]}, 1, 0]}},
poor: {$sum: {$cond: [{$lt: ["$score", 10]}, 1, 0]}}
}},
{$unset: "_id"},
{$project: {data: {$objectToArray: "$$ROOT"}}},
{$project: {
data: {$map: {
input: "$data",
in: {nmae: "$$this.k", count: "$$this.v"}
}}
}}
])
看看它在操場上的例子是如何作業的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/526572.html
