如何在mongodb中对布尔字段进行分组?
下面是一个非常简单的数据示例如何在mongodb中对布尔字段进行分组?,mongodb,Mongodb,下面是一个非常简单的数据示例 [ { “aaa”:没错, “bbb”:111, }, { “aaa”:错, “bbb”:111, } ] 那么,应该执行什么查询才能得到这样的结果呢 [ { “_id”:“0”, “BBU sum”:222, “aaa_”和“false”, “aaa_或”:正确 } ] 实际上,我已经尝试过这样的查询 db.collection.aggregate([ { “$group”:{ “_id”:“0”, “BBU金额”:{ $sum:“$bbb” }, “aaa_
[
{
“aaa”:没错,
“bbb”:111,
},
{
“aaa”:错,
“bbb”:111,
}
]
那么,应该执行什么查询才能得到这样的结果呢
[
{
“_id”:“0”,
“BBU sum”:222,
“aaa_”和“false”,
“aaa_或”:正确
}
]
实际上,我已经尝试过这样的查询
db.collection.aggregate([
{
“$group”:{
“_id”:“0”,
“BBU金额”:{
$sum:“$bbb”
},
“aaa_和”:{
“$and”:[“$aaa”,正确]
},
“aaa_或”:{
“$or”:[“$aaa”,假]
}
}
}
])
但是Mongo游乐场抱怨查询失败:(Location40237)$and累加器是一元运算符
,这很让人困惑
您也可以在这里找到这个简单的测试用例
另外,我在Google和Stackoverflow上都搜索过类似的问题,但我找不到
提前谢谢 您可以执行以下逻辑
db.collection.aggregate([
{
"$group": {//Group by desired id
"_id": null,
"sum": {//Sum the value
"$sum": "$bbb"
},
"aaa_and": {
"$sum": {
"$cond": {
"if": {
"$eq": [
"$aaa",
true
]
},
"then": 1, //If true returns 1
"else": 0 // else 0
}
}
},
"total": { //helper to do the logic
$sum: 1
}
}
},
{
$project: {
aaa_and: {
"$eq": [//If total matches with number of true, all are true
"$total",
"$aaa_and"
]
},
aaa_or: {
"$ne": [//if value greater than 0, then there is at least one true
"$aaa_and",
"0"
]
},
sum: 1
}
}
])
与“$sum”、“$and”和“$or”不同,它们不是可在“$group”中使用的聚合运算符。您可以将所有“aaa”字段临时保存到数组中,然后使用“$project”运算符处理数据
db.collection.aggregate([
{
"$group": {
"_id": "0",
"sum": {
"$sum": "$bbb"
},
"aaa_all": {
"$push": "$aaa"
}
}
},
{
"$project": {
"sum": 1,
"aaa_and": {
"$allElementsTrue": "$aaa_all"
},
"aaa_or": {
"$anyElementTrue": "$aaa_all"
}
}
}
])
情况是这样的:非常好的解决方案!非常感谢。非常简洁易懂的解决方案!非常感谢。只要一个简单的问题,
“sum”:1在$project
部分中是什么意思?我发现我可以使用1、2或其他东西,两者都可以使用。对于空数组,AllegementStrue将返回true。记住这一点。这是一个很好的方法+1@kaixinliu您可以使用任何正数。@Gibbs,是的,您是正确的,我们需要注意“空数组问题”。谢谢。@kaixinliu“sum”:1表示直接投影“sum”字段。正如吉布斯提到的,任何正数都可以。