下午对数据查询进行了代码测试:
package main import ( "crypto/rand" "encoding/hex" "fmt" "labix.org/v2/mgo" "labix.org/v2/mgo/bson" "time" ) var ( mgoSession *mgo.Session databaseName = "myDB" tbl_person = "persons" tbl_log = "logs" ) type Person struct { Id string Name string Inserted time.Time } type Log struct { LogId string Log string LogUser mgo.DBRef Inserted time.Time } func main() { session, err := mgo.Dial("localhost:27017") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) session.DB(databaseName).DropDatabase() c := session.DB(databaseName).C(tbl_person) d := session.DB(databaseName).C(tbl_log) _ = c.Insert(&Person{"111", "ssl1", time.Now()}) _ = c.Insert(&Person{"222", "ssl1", time.Now()}) _ = c.Insert(&Person{"333", "ssl1", time.Now()}) for i := 0; i < 10; i++ { _ = d.Insert(&Log{GenerateUUID(), "这是一个测试日志", mgo.DBRef{tbl_person, "111", databaseName}, time.Now()}) } for i := 0; i < 10; i++ { _ = d.Insert(&Log{GenerateUUID(), "这是一个测试日志", mgo.DBRef{tbl_person, "222", databaseName}, time.Now()}) } for i := 0; i < 10; i++ { _ = d.Insert(&Log{GenerateUUID(), "这是一个测试日志", mgo.DBRef{tbl_person, "333", databaseName}, time.Now()}) } personcount, _ := c.Find(bson.M{}).Count() fmt.Println(personcount) logcount, _ := d.Find(bson.M{}).Count() fmt.Println(logcount) //在这里loguser.$db值未用变量,测试了一下数据库名大小敏感问题,结果结果:数据库区分大小写!!!! //如果是在同一个数据库中,loguser.$db可不写 p1logcount, _ := d.Find(bson.M{"loguser.$ref": tbl_person, "loguser.$id": "111", "loguser.$db": "myDB"}).Count() fmt.Println(p1logcount) result1 := []Log{} err = d.Find(bson.M{}).All(&result1) fmt.Println(result1) } // http://www.ashishbanerjee.com/home/go/go-generate-uuid func GenerateUUID() string { uuid := make([]byte, 16) n, err := rand.Read(uuid) if n != len(uuid) || err != nil { return "" } uuid[8] = 0x80 // variant bits see page 5 uuid[4] = 0x40 // version 4 Pseudo Random, see page 7 return hex.EncodeToString(uuid) }
结果正确:
[ `run` | done: 179.164361ms ] 3 30 10
参考: