The method of Golang operation MongoDB _golang

Source: Internet
Author: User
Tags email string mongodb

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.