douman6679 2017-08-18 05:21
浏览 394
已采纳

使用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 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,
                },
            }},
        },
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏