mgo中DBRef-数据查询测试

下午对数据查询进行了代码测试:

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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)
}
 
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

参考:

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。