The method of Golang operation MongoDB is described in this paper. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
Package Main
Import (
"FMT"
"Launchpad.net/mgo"
"Launchpad.net/mgo/bson"
)
Type Mail struct {
Id Bson. ObjectId "_id"
Name string
Email string
}
Func Main () {
Connecting to a database
Session, Err: = MgO. Dial ("127.0.0.1")
If Err!= nil {
Panic (ERR)
}
Defer session. Close ()
Get the database, get the collection
C: = Session. DB ("Test"). C ("Mail")
Storing data
M1: = Mail{bson. Newobjectid (), "User1", "user1@dotcoo.com"}
M2: = Mail{bson. Newobjectid (), "User1", "user2@dotcoo.com"}
M3: = Mail{bson. Newobjectid (), "User3", "user3@dotcoo.com"}
M4: = Mail{bson. Newobjectid (), "User3", "user4@dotcoo.com"}
Err = C.insert (&m1, &m2, &M3, &M4)
If Err!= nil {
Panic (ERR)
}
Reading data
MS: = []mail{}
Err = C.find (&bson. m{"name": "User3"}). All (&MS)
If Err!= nil {
Panic (ERR)
}
Display data
For I, M: = Range ms {
Fmt. Printf ("%s,%d,%s\n", M.id.hex (), I, M.email)
}
}
I hope this article will help you with your go language program.