使用mgov2进行Mongodb查询

时间:2017-08-18 05:21:32

标签: mongodb go mgo

我在各种渠道上进行了一系列端点测试。该集合中的示例文档是:

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

我正在查询这个结果如下:

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

但是我得到了错误的成功和失败率。我在golang中的当前查询看起来像:

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"},
        },
    },
}

我在计算成功次数方面做错了。我无法想象做得对。我刚刚开始使用mgo和golang。

提前致谢

1 个答案:

答案 0 :(得分:1)

您需要使用$cond进行条件计数。例如,以下步骤计算所有测试,失败测试和成功测试:

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,
            },
        }},
    },
}