获取总用户列表以及 mongodb 中符合 OR 条件的活跃用户

Get total users list along with the active users in mongodb matched on OR condition

Table : 
user: A,
active_1 : "true",
active_2 : "false",
is_user : "true"

user: B,
active_1 : "false",
active_2 : "true",
is_user : "true"

user: C,
active_1 : "false",
active_2 : "false",
is_user : "true"

预期输出:

{
    "_id" : null,
    "total" : 3,
    "count" : 2
}

我需要检查 active_1 或 active_2 是否为真,并得到类似于 total 的输出,它表示 no.of 用户总数,即 A、B 和 C。 count 表示 active_1 或 active_2 为真的用户。它应该检查 is_user true 这是强制性的

我试过的代码:

db.getCollection('mycollections').aggregate([{'$match': 'is_user': 'true'}}, 
    {'$group': {'count': {'$sum': 
        {'$or':[
        {
          "active_1": "true"
        },
        {
          "active_2": "true"
        }
      ]}},
        'total': {'$sum': 1}, '_id': 0}}, 
        {'$project': {'count': '$count', 'total': '$total', '_id': 0}}]
)

结果是 count:0,总数:3。但这不是我所期望的。

你已经很接近了,你只需要使用像$cond这样的东西来实现:

db.collection.aggregate([
  {
    "$group": {
      "count": {
        "$sum": {
          $cond: [
            {
              "$or": [
                {
                  $eq: [
                    "$active_1",
                    "true"
                  ]
                },
                {
                  $eq: [
                    "$active_2",
                    "true"
                  ]
                }
              ]
            },
            1,
            0
          ]
        }
      },
      "total": {
        "$sum": 1
      },
      "_id": 0
    }
  },
  
])

MongoPlayground