問題:
問題:Mongo 聚合需要查詢花費約500-650毫秒返回,儘管使用mgo.
func (r userRepo) GetUserByID(id string) (User, error) { info, err := db.Info() if err != nil { log.Fatal(err) } session, err := mgo.Dial(info.ConnectionString()) if err != nil { log.Fatal(err) } defer session.Close() var user User c := session.DB(info.Db()).C("users") o1 := bson.M{"$match": bson.M{"_id": id}} o2 := bson.M{"$project": bson.M{ "first": "$first", "last": "$last", "email": "$email", "fb_id": "$fb_id", "groups": "$groups", "fulfillments": "$fulfillments", "denied_requests": "$denied_requests", "invites": "$invites", "requests": bson.M{ "$filter": bson.M{ "input": "$requests", "as": "item", "cond": bson.M{ "$eq": []interface{}{"$$item.active", true}, }, }, }, }} pipeline := []bson.M{o1, o2} err = c.Pipe(pipeline).One(&user) if err != nil { return user, err } return user, nil }
範例查詢:
問題:查詢效能緩慢是否有明顯的原因?
提示: mgo.Dial() 方法在每個之前被呼叫
回答:是的,性能緩慢可歸因於重複呼叫mgo.Dial()。這種方法每次都會與MongoDB伺服器建立連接,可能需要幾百毫秒的時間。若要解決此問題,請建立一個全域會話變量,在啟動時建立一次連接(例如,在套件 init() 函數中),然後使用該會話(或其副本)進行所有查詢。
var session *mgo.Session var info *db.Inf // Use your type here func init() { var err error if info, err = db.Info(); err != nil { log.Fatal(err) } if session, err = mgo.Dial(info.ConnectionString()); err != nil { log.Fatal(err) } } func (r userRepo) GetUserByID(id string) (User, error) { sess := session.Clone() defer sess.Close() var user User c := sess.DB(info.Db()).C("users") o1 := bson.M{"$match": bson.M{"_id": id}} o2 := bson.M{"$project": bson.M{ "first": "$first", "last": "$last", "email": "$email", "fb_id": "$fb_id", "groups": "$groups", "fulfillments": "$fulfillments", "denied_requests": "$denied_requests", "invites": "$invites", "requests": bson.M{ "$filter": bson.M{ "input": "$requests", "as": "item", "cond": bson.M{ "$eq": []interface{}{"$$item.active", true}, }, }, }, }} pipeline := []bson.M{o1, o2} err = c.Pipe(pipeline).One(&user) if err != nil { return user, err } return user, nil }
以上是為什麼我的 mgo 查詢需要 500-650 毫秒才能執行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!