This is a creation in Article, where the information may have evolved or changed.
2014-1-25
When you design a MONGO database, you encounter a problem where the log information table needs to reference the data from the people information table. If it's a structured database, you don't have to think much about it. As a result of the new access to unstructured databases, as the number of logs in the book If the use of embedded data will produce too many variables (do not know that this is not reasonable, such as people often jumping in various departments will cause the data to change frequently ^_^!), so you need to use the reference Data mode. Today, we write a test demo that inserts data, and you have time to make a query.
Package Mainimport ("Crypto/rand" "Encoding/hex" "FMT" "Labix.org/v2/mgo" "Labix.org/v2/mgo/bson" "Time") Var ( Mgosession *mgo. Sessiondatabasename = "MyDB" Tbl_person = "persons" Tbl_log = "logs") type person struct {Id Stringname stri nginserted time. Time}type Log struct {logid stringlog stringloguser MgO. dbrefinserted 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) Tid: = Generateuuid () Err = C.insert (&person{tid, "SSL", time. Now ()}) if Err! = Nil {panic (err)}err = D.insert (&log{generateuuid (), "This is a test log", MgO. Dbref{tbl_person, Tid, databaseName}, time. Now ()}) if Err! = Nil {panic (err)}result: = []person{}err = C.find (Bson. m{}). All (&result) if err! = Nil {panic (err)}fmt. PRINTLN (Result) RESULT1: = []log{}err = D.find (Bson. m{}). All (&resulT1) fmt. Println (RESULT1)}//http://www.ashishbanerjee.com/home/go/go-generate-uuidfunc generateuuid () string {uuid: = make ([ ]byte, +) n, err: = Rand. Read (UUID) if n! = Len (uuid) | | Err! = Nil {return ""}uuid[8] = 0x80//Variant bits see page 5uuid[4] = 0x40//version 4 Pseudo Random, see page 7return Hex. Encodetostring (UUID)}
It uses two sets, a person information, a log message, and the main test is a reference to the log table to insert the person's information. The results are as follows:
Done 2 . 279229602s] All-in-ten:14.212 +0800 CST}] ---£º16.241 +0800 CST}]
Reference:
Database References
MongoDB dbref (Associative insert, query, delete) instance in depth
MongoDB Federated Query
Go (#golang) and MongoDB using MgO
There is some example to use Dbref?