1. 程式人生 > >Golang+Mgo 實現對於MongoDB的正則表示式查詢

Golang+Mgo 實現對於MongoDB的正則表示式查詢

1.xxdb.go程式內容如下

package xxdb


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

const URL = "127.0.0.1:27017"

// dial to db
func Dial(db, collection string) (*mgo.Session, *mgo.Collection, error) {
var ses *mgo.Session
var col *mgo.Collection
var err error
if ses, err = mgo.Dial(URL); err != nil {
return nil, nil, xxerr("Dial", "", err)
}
ses.SetMode(mgo.Monotonic, true)
col = ses.DB(db).C(collection)
return ses, col, nil

}

//根據查詢條件以切片形式返回多個mongodb中的文件
func FindMulti(db, collection string, condition, selection bson.M, limit int) ([]interface{}, error) {
ses, col, err := Dial(db, collection)
defer ses.Close()
if err != nil {
return nil, xxerr("FindMulti", "", err)
}
iter := col.Find(condition).Select(selection).Limit(limit).Iter()
var result []interface{}
err = iter.All(&result)
if err != nil {
return nil, xxerr("FindMulti", "", err)
}
return result, nil
}

2.user.go 程式內容如下

package user

import (
"../xxdb"
"../xxio"
"gopkg.in/mgo.v2/bson"
"strings"
)

//根據使用者名稱搜尋好友,通過正則表示式實現模糊搜尋
func SearchByName(uid string, selection bson.M, limit int) ([]interface{}, error) {
if uid == "" {
return nil, nil
}
result, err := xxdb.FindMulti("sylm", "user", bson.M{"info.name": bson.M{"$regex": uid, "$options": "$i"}}, selection, limit)
return result, err
}

"$regex"表示字串匹配,"$options": "$i"表示不區分大小寫