实际上都是围绕正则来写的,看大家喜欢那种写法
package main import ( "fmt" "labix.org/v2/mgo" "labix.org/v2/mgo/bson" "time" ) type User struct { Name string //用户名称 Key string //关键字 Modified time.Time //修改时间 } func main() { str1 := "aaaaaaaaaaaaaaaaaaaaaaraaaaaaaaaaaaaa" str2 := "bbbbbbbbbbbbbbbbbbbbbbbbbhbbbbbbbbbbb" str3 := "xxxxxxxxxxxxxxxxxxxxx" session, err := mgo.Dial("localhost:27017") if err != nil { panic(err) } defer session.Close() c := session.DB("lsoa").C("users") c.DropCollection() for i := 0; i < 10; i++ { if i%2 == 0 { err = c.Insert(&User{fmt.Sprintf("cst%d", i), str1, time.Now()}) } else { err = c.Insert(&User{fmt.Sprintf("est%d", i), str2, time.Now()}) } } err = c.Insert(&User{fmt.Sprintf("cest%d", 12), str3, time.Now()}) ac, err := c.Find(bson.M{}).Count() //第一种写法 // query :=bson.M{"$or":[]bson.M{bson.M{"name": bson.M{"$regex": bson.RegEx{"ce", "i"}}}, // bson.M{"key": bson.M{"$regex": bson.RegEx{"x", "i"}}}}}
//第二种写法 regex1 := bson.RegEx{"ce", "i"} regex2 := bson.RegEx{"x", "i"}
query := bson.M{"$or": []bson.M{bson.M{"name": regex1}, bson.M{"key": regex2}}}
fmt.Println(query)
count, err := c.Find(query).Count()
fmt.Printf("All Count: %d ,Filter count:%d", ac, count)
}