[英]mongodb aggregation gives error in golang
I want group methods types and count them according to their types.these methods are strings. 我想要分组方法类型并根据它们的类型对其进行计数。这些方法是字符串。 I wrote below code.But it gives an error. 我写了下面的代码,但这给出了一个错误。
pipeline := []bson.D{
bson.D{
{"$unwind", "$method"},
},
bson.D{
{"$group", bson.M{"_id": "$method", "count": bson.M{"$sum": 1}}},
},
query := bson.D{
{"aggregate", "API_ACCESS_LOGS"}, // useragents is a collection name
{"pipeline", pipeline},
}
err = session.DB("vamps-logs").Run(query, &methods)
It gives below error. 它给出以下错误。
2018/02/06 09:58:33 http: panic serving 127.0.0.1:53973: runtime error: index out of range goroutine 92 [running]: 2018/02/06 09:58:33 http:紧急服务127.0.0.1:53973:运行时错误:索引超出范围goroutine 92 [正在运行]:
please help me to correct this 请帮助我纠正这个问题
Hi this is a sample code I modified to use pipelines with MgO golang. 嗨,这是我修改为将管道与MgO golang一起使用的示例代码。 Watch It and try to apply it. 观看并尝试应用它。 package main 包主
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)
}
Dataset in the mongoDB 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 放出
Type: [{POST 2} {PUT 2} {GET 2}] 类型:[{POST 2} {PUT 2} {GET 2}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.