首页 文章资讯内容详情

golang-mongodb范例

2026-06-01 4 花语

本文内容纲要:

1packagemain 2 3import( 4"log" 5 6"gopkg.in/mgo.v2" 7"gopkg.in/mgo.v2/bson" 8) 9 10typeAddressstruct{ 11Addressstring 12} 13typeLocationstruct{ 14Longitudefloat64 15Latitudefloat64 16} 17 18typePersonstruct{ 19Idbson.ObjectId`bson:"_id"` 20Namestring 21Age_Intint 22Address[]Address 23LocationLocation 24} 25 26funcmain(){ 27log.SetFlags(log.Flags()|log.Lshortfile) 28//连接 29session,err:=mgo.Dial("127.0.0.1:27017") 30iferr!=nil{ 31log.Println(err) 32return 33} 34//设置模式 35session.SetMode(mgo.Monotonic,true) 36//获取文档集 37collection:=session.DB("test").C("person") 38//创建索引 39index:=mgo.Index{ 40Key:[]string{"name"},//索引字段,默认升序,若需降序在字段前加- 41Unique:true,//唯一索引同mysql唯一索引 42DropDups:true,//索引重复替换旧文档,Unique为true时失效 43Background:true,//后台创建索引 44} 45iferr:=collection.EnsureIndex(index);err!=nil{ 46log.Println(err) 47return 48} 49iferr:=collection.EnsureIndexKey("$2dsphere:location");err!=nil{//创建一个范围索引 50log.Println(err) 51return 52} 53//添加记录 54person:=Person{ 55Id:bson.NewObjectId(), 56Name:"逍遥", 57Age_Int:24, 58Address:[]Address{ 59Address{ 60Address:"仙灵岛", 61}, 62}, 63Location:Location{ 64Longitude:1, 65Latitude:1, 66}, 67} 68iferr:=collection.Insert(person);err!=nil{ 69log.Println(err) 70return 71} 72//查找记录 73newPerson:=&Person{} 74iferr:=collection.Find(bson.M{"age_int":24}).One(newPerson);err!=nil{ 75log.Println(err) 76return 77} 78//修改记录 79iferr:=collection.Update(bson.M{"age_int":24},bson.M{"$set":bson.M{"age_int":26}});err!=nil{ 80log.Println(err) 81return 82} 83//删除记录 84//iferr:=collection.Remove(bson.M{"age_int":26});err!=nil{ 85//log.Println(err) 86//return 87//} 88//位置搜索 89selector:=bson.M{ 90"location":bson.M{ 91"$near":bson.M{ 92"$geometry":bson.M{ 93"type":"Point", 94"coordinates":[]float64{1,1}, 95}, 96"$maxDistance":1, 97//"$minDistance":0, 98}, 99}, 100} 101iferr:=collection.Find(selector).One(newPerson);err!=nil{ 102log.Println(err) 103return 104} 105// 106session.Close() 107}

本文内容总结:

原文链接:https://www.cnblogs.com/--xiaoyao--/p/5284685.html