获取总用户列表以及在OR条件下匹配的mongodb中的活动用户 [英] Get total users list along with the active users in mongodb matched on OR condition

查看:266
本文介绍了获取总用户列表以及在OR条件下匹配的mongodb中的活动用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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的输出,该输出指示用户总数为A,B和C.计数表明具有active_1或active_2的用户为true .它应该检查is_user为true,这是强制性的

I need to check either the active_1 or active_2 is true and get the output as like total which indicates the total no.of users which is A,B and C. The count indicates the users who have either active_1 or active_2 is true. It should check is_user true which is mandatory

我尝试过的代码:

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.但这不是我所期望的.

Result is count:0 and total : 3. But that is not what I have expected.

推荐答案

您非常接近,您只需要使用

You're very close, you just need to use something like $cond to achieve this:

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

MongoPlayground

这篇关于获取总用户列表以及在OR条件下匹配的mongodb中的活动用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆