douman6679
2017-08-18 05:21 阅读 192

使用mgov2的Mongodb查询

I have a collection of endpoint point tests conducted on various channels. A sample document from the collection is:

{
    "_id" : ObjectId("59959b30c699811077751b12"),
    "teststatus" : "Fail",
    "channelname" : "HouseController",
    "timestamp" : ISODate("2017-08-17T13:15:53.170Z"),
    "testid" : "llpKIgIfiiquqkSApwNn"
}

I am querying this to project the result something like this:

[
  {
    "Fail": 20,
    "Success Count": 30,
    "Total": 50,
    "channel": "c3"
  }, ...

But I am getting the wrong count for success and fail rate. My current query in golang looks like:

o1:=  bson.M{
    "$project" :bson.M{
        "channel": "$channelname",
        "time":"$timestamp",
        "teststatus" : "$teststatus",
        "_id":1,
    },
}
o2:=  bson.M{
    "$group" :bson.M{
        "_id": "$channel",
        "Success": bson.M{
            "$sum":bson.M{ "$eq" :"teststatus","Pass"},
        },
        "Total": bson.M{
            "$sum": 1,
        },
    },
}
o3:=  bson.M{
    "$project" :bson.M{
        "channel": "$_id",
        "Success Count":"$Success",
        "Total" : "$Total",
        "_id":0,
        "Fail": bson.M{
            "$subtract": []interface{}{"$Total", "$Success"},
        },
    },
}

I am doing wrong in the counting of success count. I just cant figure to do it right. I have just started with mgo and golang.

Thanks in advance

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dsogx84602 dsogx84602 2017-08-18 07:48

    You need to use $cond to do conditional counting. For example the following counts all tests, failed ones and successful ones in one step:

    o2 := bson.M{
        "$group" :bson.M{
            "_id": "$channel",
            "Total": bson.M{
                "$sum": 1,
            },
            "Success": bson.M{"$sum": bson.M{
                "$cond": []interface{}{
                    bson.M{ "$eq": []interface{}{"$teststatus", "Pass"}},
                    1, 0,
                },
            }},
            "Fail": bson.M{"$sum": bson.M{
                "$cond": []interface{}{
                    bson.M{"$eq": []interface{}{"$teststatus", "Fail"}},
                    1, 0,
                },
            }},
        },
    }
    
    点赞 评论 复制链接分享

相关推荐