1. 程式人生 > >mgo 實現mongodb中的sortByCount方法

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