MongoDB:GROUP BY有条件地在布尔字段上累计COUNT

时间:2018-08-19 03:47:30

标签: mongodb nosql mongodb-query

我在Mongo有一个三栏式的收藏集,例如:

{
    "_id" : ObjectId("5b6db9e1d1b00b1b906c0225"),
    "ip" : "127.0.0.1",
    "hostFqdn" : "host-1",
    "active" : true
},
{
    "_id" : ObjectId("5b6db9e1d1b00b1b906c0226"),
    "ip" : "127.0.0.2",
    "hostFqdn" : "host-1",
    "active" : false
},
{
    "_id" : ObjectId("5b6db9e1d1b00b1b906c0227"),
    "ip" : "127.0.0.3",
    "hostFqdn" : "host-2",
    "active" : true
},
{
    "_id" : ObjectId("5b6db9e1d1b00b1b906c0228"),
    "ip" : "127.0.0.4",
    "hostFqdn" : "host-2",
    "active" : true
},
{
    "_id" : ObjectId("5b6db9e1d1b00b1b906c0229"),
    "ip" : "127.0.0.5",
    "hostFqdn" : "host-2",
    "active" : false
},
{
    "_id" : ObjectId("5b6f61204b0f134f6635a74b"),
    "ip" : "127.0.0.6",
    "hostFqdn" : "host-3",
    "active" : false
}

我需要选择所有最多具有一个活动IP的hostFqdn(即,对于以上数据,响应将为host-1host-3)。

到目前为止,我得到的是:

db['hosts.status'].aggregate([[{
    "$group": {
        _id: "$hostFqdn",
        "true": {
            "$sum": {
                "$cond": [{ "$lte": [{ "active": "$active" }, 1]}, 1, 0]
            }
        }
    }
}]

但这会返回计数为0的所有三个hostFqdn。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

db.collection.aggregate([
  { "$group": {
    "_id": "$hostFqdn",
    "true": {
      "$sum": {
        "$cond": [{ "$eq": [ "$active", true ]}, 1, 0]
      }
    }
  }}
])

答案 1 :(得分:0)

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $group: {
                _id: '$hostFqdn',
                status: {
                    $push: '$active'
                }
            }
        },

        // Stage 2
        {
            $project: {
                v: {
                    $cond: {
                        if: {
                            $ne: [{
                                $indexOfArray: ['$status', true]
                            }, -1]
                        },
                        then: {
                            $sum: 1
                        },
                        else: 0
                    }
                }



            }
        },

    ]

    // Created with Studio 3T, the IDE for MongoDB - https://studio3t.com/

);