MongoDB:计算匹配查询的文档的真值和假值总数
MongoDB: Count total number of true and false values for documents matching a query
我的问题和这个完全一样
我采用了相同的解决方案,但没有得到所需的输出。
我在数据库中有一些产品记录。其中有些是免费的,有些则不是。我想检索免费和非免费产品的数量。这是我的记录
{ "_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
}
可以跳过第一组,直接用$cond
求isFree
:
db.collection.aggregate([
{
"$group": {
_id: null,
free: {
$sum: {
$cond: ["$isFree",1,0]
}
},
nonFree: {
$sum: {
$cond: ["$isFree",0,1]
}
}
}
},
{$project:{_id:0}}
])
我的问题和这个完全一样
我采用了相同的解决方案,但没有得到所需的输出。
我在数据库中有一些产品记录。其中有些是免费的,有些则不是。我想检索免费和非免费产品的数量。这是我的记录
{ "_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
}
可以跳过第一组,直接用$cond
求isFree
:
db.collection.aggregate([
{
"$group": {
_id: null,
free: {
$sum: {
$cond: ["$isFree",1,0]
}
},
nonFree: {
$sum: {
$cond: ["$isFree",0,1]
}
}
}
},
{$project:{_id:0}}
])