我的問題與此完全相同
MongoDB 計算與查詢匹配的檔案的真偽值總數
我遵循了相同的解決方案,但沒有獲得所需的輸出。
我在資料庫中有一些產品記錄。其中有些是免費的,有些則不是。我想檢索免費和非免費產品的數量。這是我的記錄
{ "_id" : ObjectId("54abcdbeba070410146d6073"), "name" : "Product 1", "isFree" : true}
{ "_id" : ObjectId("54afe32fec4444481b985711"), "name" : "Product 2", "isFree" : false}
{ "_id" : ObjectId("54b66de68dde7a0c19be987b"), "name" : "Product 3", "isFree" : false}
{ "_id" : ObjectId("54b66de68dde7a0c19bc897d"), "name" : "Product 4", "isFree" : false}
我期望輸出為:
{
"free": 1,
"nonFree": 3
}
這是我的查詢:
db.collection.aggregate([
{
"$group": {
"_id": "$isFree",
"count": {
"$sum": 1
}
}
},
{
"$group": {
_id: null,
free: {
$sum: {
$cond: ["_id",1,0]
}
},
nonFree: {
$sum: {
$cond: ["_id",0,1]
}
}
}
}
])
我得到的輸出為:
{
"_id": null,
"free": 2,
"nonFree": 0
}
uj5u.com熱心網友回復:
可以跳過第一組,直接使用$cond來求值isFree:
db.collection.aggregate([
{
"$group": {
_id: null,
free: {
$sum: {
$cond: ["$isFree",1,0]
}
},
nonFree: {
$sum: {
$cond: ["$isFree",0,1]
}
}
}
},
{$project:{_id:0}}
])
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362978.html
