mongodb聚合在golang中出错

时间:2018-02-06 04:42:21

标签: mongodb go aggregation-framework mgo

我想要组方法类型并根据它们的类型对它们进行计数。这些方法是字符串。我在下面写了代码。但它给出了一个错误。

#!/usr/bin/env expect
spawn git rebase -i HEAD~2

# down, delete word, insert 's' (for squash), Escape, save and quit
send "jdwis \033:wq\r"

expect "# This is a"

# down 4, delete 3 lines, save and quit
send "4j3d:wq\r"

interact

它给出了以下错误。

2018/02/06 09:58:33 http:恐慌服务127.0.0.1:533973:运行时错误:索引超出范围 goroutine 92 [跑步]:

请帮我纠正这个

1 个答案:

答案 0 :(得分:0)

嗨,这是我修改为使用带有MgO golang的管道的示例代码。观看它并尝试应用它。     包主要

import ("fmt"
    "log"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type Method struct {
        Type string `json:"Type" bson:"Type"`
        Host float64 `json:"Host" bson:"Host"`
}

type Out struct {
        Type string `json:"Type" bson:"Type"`
        Count float64 `json:"count" bson:"count"`
}

func main() {

        session, err := mgo.Dial("localhost")
        if err != nil {
                panic(err)
        }
        defer session.Close()

        // Optional. Switch the session to a monotonic behavior.
        session.SetMode(mgo.Monotonic, true)

        c := session.DB("test").C("api")
        // err = c.Insert(&Method{"GET", 1.0},
           //         &Method{"PUT", 2.0},
           //         &Method{"POST", 2.0})
        if err != nil {
                log.Fatal(err)
        }

        pipe := c.Pipe(
                []bson.M{
                    bson.M{
                        "$unwind":"$Type",
                    },
                    bson.M{
                        "$group":bson.M{
                        "_id":"$Type", 
                        "count":bson.M{"$sum":1,},
                        },
                    },
                    bson.M{
                        "$project":bson.M{
                        "Type":"$_id" , "count":"$count",
                        },
                    },
                },
            )

        result := []Out{}
        // err = c.Find(bson.M{"Type": "GET" }).One(&result)
            err = pipe.All(&result)

        if err != nil {
                log.Fatal(err)
        }

        fmt.Println("Type:", result)
}

mongoDB中的数据集

/* 1 */
{
    "_id" : ObjectId("5a794efd49d755038cc60307"),
    "Type" : "GET",
    "Host" : 1.0
}

/* 2 */
{
    "_id" : ObjectId("5a794efd49d755038cc60308"),
    "Type" : "PUT",
    "Host" : 2.0
}

/* 3 */
{
    "_id" : ObjectId("5a794efd49d755038cc60309"),
    "Type" : "POST",
    "Host" : 2.0
}

/* 4 */
{
    "_id" : ObjectId("5a794f3149d755038cc6031a"),
    "Type" : "GET",
    "Host" : 1.0
}

/* 5 */
{
    "_id" : ObjectId("5a794f3149d755038cc6031b"),
    "Type" : "PUT",
    "Host" : 2.0
}

/* 6 */
{
    "_id" : ObjectId("5a794f3149d755038cc6031c"),
    "Type" : "POST",
    "Host" : 2.0
}

Out put

输入:[{POST 2} {PUT 2} {GET 2}]