【问题标题】:how to return count value for two match condition by grouping in mongoose?如何通过在猫鼬中分组返回两个匹配条件的计数值?
【发布时间】:2020-04-11 08:14:16
【问题描述】:

我希望我的输出 json 如下所示,

[ {
        "_id": "IT",
        "count 1": 1,
        "count 2": 1,

    },
    {
        "_id": "CSE",
        "count1": 1,
        "count2": 2,

    },

  
]

我在猫鼬中尝试了以下查询

{
    $match: {

        
        riskstatus: { $in: ["Closed", "Deffered"] },
        riskstatus: { $in: [ "Open"] },
    }
},

{

    "$group": {
        "_id": "$phase",
        "count1": { "$sum": 1 },
       "count2": { "$sum": 1 },

    },

}
        

我的输入集合是

{"_id":"5df5ca73bb1c4526948e2421","comment":"test","status":"Open","phase":"CSE"}
{"_id":"5df5ca73bb1c4526948e2422","comment":"test","status":"closed","phase":"IT"}
{"_id":"5df5ca73bb1c4526948e2422","comment":"test","status":"Closed","phase":"CSE"}
{"_id":"5df5ca73bb1c4526948e2422","comment":"test","status":"Open","phase":"IT"}
{"_id":"5df5ca73bb1c4526948e2422","comment":"test","status":"Open","phase":"CSE"}

如何通过上述匹配条件检索同一组的两个计数值以达到此结果?

我最近尝试的是

Risk.aggregate([
        { $match: { $or: [ { status: {$in: ["Closed", "Deffered"]} }, { status: {$in: ["Open"] } } ] } },
  

        {

            "$group": {
                "_id": "$phase",
                " count1": { "$sum": 1 },
                "count2": { "$sum": 1 },

            },

        }

【问题讨论】:

标签: node.js mongodb


【解决方案1】:

请使用该查询

     db.posts.aggregate(
    {
        $group: {
            _id: { 'id': '$phase', 'status': '$status' },
            count_1: { '$sum': 1 },
        }
    },
    { $project: { '_id': 0, 'depart': '$_id.id', 'status': '$_id.status', 'count_1': 1 } }
    , {
        $group: {
            _id: '$depart',
            data: {
                '$push': {
                    'depart': '$depart',
                    'count_1': {
                        $cond: [{ $eq: ["$status", 'Open'] }, '$count_1', 0]
                    },
                    'count_2': {
                        $cond: [{ $eq: ["$status", 'Closed'] }, '$count_1', 0]
                    }
                    ,
                    'count_3': {
                        $cond: [{ $eq: ["$status", 'Deffered'] }, '$count_1', 0]
                    }

                },
            }
        }
    },
      { $project: 
      {'name':'$_id','_id':0, 
      openCount: { $max: "$data.count_1"}, 
      Othercount: {  
          $add:[ 
              {$max: "$data.count_2"},
              {$max: "$data.count_3"}]

      } 

      }}

)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2016-03-31
    • 2018-09-07
    • 2020-05-25
    • 1970-01-01
    • 2021-09-12
    • 2021-03-28
    相关资源
    最近更新 更多