MgO is the Golang drive of MongoDB, the test code:
//mgotest Project Main.go PackageMainImport ( "FMT" "Time" "Gopkg.in/mgo.v2" "Gopkg.in/mgo.v2/bson") type User struct {Id Bson. ObjectId ' Bson:"_ID"' Username string ' Bson:"Name"' Pass string ' Bson:"Pass"' regtime Int64 ' Bson:"Regtime"' interests []string ' Bson:"Interests"`}ConstURL String = "127.0.0.1:27017"var c*MgO. Collectionvar Session*MgO. Sessionfunc (user user) ToString () string {returnFmt. Sprintf ("% #v", user)} Func init () {session, _=MgO. Dial (URL)//Switch to DatabaseDB: = Session. DB ("blog") //Switch to Collectionc = db. C ("Mgotest")}//New Datafunc Add () {//defer session. Close ()STU1: =New(User) stu1. Id=Bson. Newobjectid () stu1. Username= "Stu1_name"STU1. Pass= "Stu1_pass"STU1. Regtime=Time . Now (). Unix () stu1. Interests= []string{"chess", "swimming", "running"} ERR:=C.insert (STU1)ifErr = =Nil {fmt. Println ("Insert Succeeded") } Else{fmt. Println (Err. Error ()) defer panic (ERR)}}//Enquiryfunc Find () {//defer session. Close ()var users []user//C.find (nil). All (&users)C.find (Bson. m{"name": "Stu1_name"}). All (&users) for_, Value: =range Users {fmt. Println (value. ToString ())}//query according to ObjectidIDSTR: = "577fb2d1cde67307e819133d"objectId:=Bson. Objectidhex (idstr) User:=New(User) c.find (Bson. m{"_ID": ObjectId}). One (user) fmt. PRINTLN (user)}//Modify by IDfunc Update () {interests:= []string{"chess", "swimming", "running"} ERR:= C.update (Bson. m{"_id": Bson. Objectidhex ("577fb2d1cde67307e819133d")}, Bson. m{"$set": Bson. m{"Name": "Modified name", "Pass": "Modified Pass", "Regtime": Time. Now (). Unix (),"Interests": Interests,}}) ifErr! =Nil {fmt. Println ("Modify Failed") } Else{fmt. Println ("Modified successfully") }}//Deletefunc del () {err:= C.remove (Bson. m{"_id": Bson. Objectidhex ("577fb2d1cde67307e819133d")}) ifErr! =Nil {fmt. Println ("Delete Failed" +Err. Error ())}Else{fmt. Println ("Delete Succeeded")}}func Main () {Add () find () update () del ()}
Golang Learn the MgO operation MongoDB