Communication with MongoDB in go language-using MgO

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Communication with MongoDB in go language-using MgO

Category: MongoDB 2013-08-28 15:52 1585 people read Comments (0) Collection Report

Recently wrote a game suit. It's all new. Go language +mongodb. Hey. about how MgO is used is not detailed. The official website is very clear. This piece is about how to use it.

Import the MgO library first.

Import (
"Labix.org/v2/mgo"
"Labix.org/v2/mgo/bson"
)

Declaring DB

var Db_dbs *mgo. Database

Statement Collection

var db_dbuserlist *mgo. Collection

Connecting to a database
Session, Err: = MgO. Dial ("127.0.0.1")

Select the DB for use

Db_dbs = Session. DB ("Jltx")

Select the corresponding collection

Db_dbuserlist = Db_dbs. C ("UserList")

That's it. You can get into the table operation. Read the MONGO authoritative guide. You just have to be a shell. Communicating with MgO to the DB will be simple.

Bson. m{} This thing is the star of the whole MgO dong. Used to turn the structure of Golang Bson.

For example, to find all the data in the info table

[CPP]View Plaincopy
  1. INFs: = []dbinfo{}
  2. Err = Db_dbinfo.find (&bson. m{}). All (&INFS)
The corresponding shell should be: Db.dbinfo.find () return all information

For example: First find all the collections where name is Enel

[CPP]View Plaincopy
  1. //Find Users   
  2. var u DBUser
  3. US := []DBUSER{}  
  4. ERR: = Db_dbuserlist.find (&bson. m{"Name": "Enel"}). All (&us)
The corresponding shell should be. Db.userlist.find ({"Name": "Enel0"}) returns the combination of hits

The above two examples are easy to see Bson. m{} and the shell's notation. Use good Bson. m{} will be able to use a good mongodb.

Here's an insert operation.

You can create a struct in go. Insert inside. Very simple.

[CPP]View Plaincopy
  1. U = Dbuser{bson. Newobjectid (), Binf. Uuiduser, CSName, Cspassword, Uint8 (Cssex)}
  2. Db_dbuserlist.insert (&u)

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.