使用 mgov2 的 Mongodb 查询

标签 mongodb go mgo

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

{
    "_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。

提前致谢

最佳答案

您需要使用$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,
            },
        }},
    },
}

关于使用 mgov2 的 Mongodb 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45749030/

相关文章:

mongodb - 限制在组中推送返回的项目

c# - 如何为 MongoDb 命名空间中的所有类注册类映射?

php - 使用 PHP 在 mongodb 中插入和检索日期和时间戳

mongodb - MongoDB 是否可用作并行处理/多实例应用程序的共享内存?

go - 如何使用 Go 创建类似 Python 的字典?

google-app-engine - 如何使用GAE/SE go112将大文件上传到Google云端存储

go - 如何循环旋转图像以在 golang 中创建 GIF?

mongodb - 如何检索 []bson.M 类型的 map

go - 如何使用 golang mgo MongoDb 驱动程序获取最后插入的 ObjectId

go - 插入golang代码怎么写?