mgo 实现mongodb中的sortByCount方法

mgo使用pipe来实现mongodb中的aggregation,所以在实现mongodb中的一些方法的时候就需要我们自己去拼接,现在使用go给大家分享一下我实现sortByCount的方法,大家可以自己自己实现一些其它的方法,如果有需要,我会继续实现一些其中的方法,希望大家多多关注!  现在直接上代码

type FieldCount struct {
Field string `json:"field"`
Count int `json:"count"`
}
type fieldGroup struct {
ID map[ string] string `bson:"_id,omitempty"`
Count int
}

/*
*
* db 数据库名字
* coll collections
* field 按照哪个字段分类
* sort 是否排序
*/
func SortByCount(db string, coll string, field string, sort bool) (fieldCount []FieldCount, err error) {
    session, err := mgo.DialWithTimeout(MONGODB_URL, time.Second)
     if err != nil {
        panic(err)
    }
     defer session.Close()
    session.SetMode(mgo.Monotonic, true)
    c := session.DB(db).C(coll)
     var pipeLine []bson.M
     if sort {
        pipeLine = []bson.M {
            bson.M{ "$group" : bson.M{ "_id" : bson.M{field : "$" + field}, "count" : bson.M{ "$sum" : 1}}},
            bson.M{ "$sort" : bson.M{ "count" : - 1}},
        }
    } else {
        pipeLine = []bson.M {
            bson.M{ "$group" : bson.M{ "_id" : bson.M{field : "$" + field}, "count" : bson.M{ "$sum" : 1}}},
        }
    }
    pipe := c.Pipe(pipeLine)
     var group []fieldGroup
err = pipe.All(&group)

     for _, g := range group {
fieldCount = append(fieldCount, FieldCount {
Field: g.ID[field],
Count: g.Count,
        })
}
     return
}


下面是我的测试方法:

func TestSortByCount(t *testing.T) {
    fieldcounttest, _ := SortByCount(constantutils.IP_URL, "logs20180601", "host", true)
     for _, item := range fieldcounttest {
        fmt.Print(item.Field + " : ")
        fmt.Println(item.Count)
    }
}


使用go中自带的测试类,大家可以运行go test -v xxxx_test.go 就可以看到输出结果了。大家有什么需要可以在下面留言,由于我也是第一次写这个东西,参考了一下其他作者的和官网的,

参考链接为:https://docs.mongodb.com/manual/reference/operator/aggregation/group/

                    https://play.golang.org/p/rDodxp22Jq

猜你喜欢

转载自blog.csdn.net/u014239709/article/details/80599198
mgo
今日推荐