gpt4 book ai didi

mongodb - 如何在 mongodb 中对 bool 字段进行分组?

转载 作者:行者123 更新时间:2023-12-05 09:07:03 24 4
gpt4 key购买 nike

这是一个非常简单的数据示例。

[
{
"aaa": true,
"bbb": 111,

},
{
"aaa": false,
"bbb": 111,

}
]

那么,应该执行什么查询才能得到这样的结果?

[
{
"_id": "0",
"bbb_sum": 222,
"aaa_and": false,
"aaa_or": true
}
]

实际上,我试过这样的查询

db.collection.aggregate([
{
"$group": {
"_id": "0",
"bbb_sum": {
"$sum": "$bbb"
},
"aaa_and": {
"$and": ["$aaa", true]
},
"aaa_or": {
"$or": ["$aaa", false]
}
}
}
])

但是 Mongo Playground 提示 query failed: (Location40237) The $and accumulator is a unary operator,这很令人困惑。

您还可以在这里找到这个简单的测试用例 https://mongoplayground.net/p/8dqtXJ93vIx

另外,我在 Google 和 Stackoverflow 上都搜索过类似的问题,但找不到。

提前致谢!

最佳答案

不像“$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"
}
}
}
])

情况是这样的:https://mongoplayground.net/p/Y-Fs_Ch9lwk

关于mongodb - 如何在 mongodb 中对 bool 字段进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65351363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com