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

不想你离开。 提交于 2020-08-08 05:13:25

问题


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"

Expected Output:

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

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

The code I have tried:

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}}]
)

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


回答1:


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



来源:https://stackoverflow.com/questions/63155077/get-total-users-list-along-with-the-active-users-in-mongodb-matched-on-or-condit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!