集合中的檔案包含title 和active欄位。該active欄位是布林值。我的目標是對title所有記錄進行分組和計數。最后,我想計算一下active正確的檔案。
此查詢進行計數,但total 和 active 始終相等。為什么條件不只計算activetrue的檔案?
這是我的管道:
[
{
"$group" : {
"_id" : {
"student?campus?title" : "$student.campus.title"
},
"total" : {
"$sum" : NumberInt(1)
},
"active" : {
"$sum" : {
"$cond" : [
{
"active" : true
},
1.0,
0.0
]
}
}
}
}
]
uj5u.com熱心網友回復:
您的代碼不起作用,因為您正在評估運算式物件而不是運算子運算式
嘗試以下作業版本:
db.collection.aggregate([
{
"$group": {
"_id": "$title",
"total": {
"$sum": 1
},
"active": {
"$sum": {
"$cond": [
"$active",
1.0,
0.0
]
}
}
}
}
])
這是Mongo 游樂場供您參考。
編輯:感謝@wernfriedDomscheit 的建議,這里有一個更簡潔的版本,使用 $toInt for MongoDB v4.0
db.collection.aggregate([
{
"$group": {
"_id": "$title",
"total": {
"$sum": 1
},
"active": {
"$sum": {
"$toInt": "$active"
}
}
}
}
])
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/391898.html
