栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

go语言连接mongoDB

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go语言连接mongoDB

文章目录
    • 官网安装
    • Docker安装
    • mongo基本命令
    • GO基本连接测试
    • GO微服务连接

官网安装

mongodb官网安装:https://docs.mongodb.com/manual/administration/install-on-linux/

Docker安装
docker search mongo
docker pull mongo
docker run -p 27017:27017 -d mongo:latest
docker exec -it containerID /bin/bash
# 实操如下
[root@k8s101 ~]# docker search mongo
NAME                                                   DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mongo                                                  MongoDB document databases provide high avai…   8611      [OK]       
mongo-express                                          Web-based MongoDB admin interface, written w…   1146      [OK]       
bitnami/mongodb                                        Bitnami MongoDB Docker Image                    173                  [OK]
mongoclient/mongoclient                                Official docker image for Mongoclient, featu…   107                  [OK]
percona/percona-server-mongodb                         Percona Server for MongoDB docker images        35                   
mongooseim/mongooseim                                  Small docker image for MongooseIM - robust a…   20                   
circleci/mongo                                         CircleCI images for MongoDB                     10                   [OK]
bitnami/mongodb-sharded                                                                                6                    
bitnami/mongodb-exporter                                                                               6                    
percona/percona-server-mongodb-operator                mongod image for PSMDB operator                 4                    
mongodbsap/mongodbdocker                                                                               2                    
rancher/mongodb-conf                                                                                   2                    
ibmcom/mongodb-ppc64le                                                                                 1                    
percona/mongodb_exporter                               A Prometheus exporter for MongoDB including …   1                    
ibmcom/mongodb                                                                                         1                    
ibmcom/mongodb-amd64                                                                                   0                    
ibmcom/mongo-java-driver-ppc64le                       Docker image for mongo-java-driver-ppc64le      0                    
ibmcom/mongodb-exporter-ppc64le                                                                        0                    
ibmcom/mongo-c-driver                                                                                  0                    
ibmcom/mongo-java-driver                                                                               0                    
ibmcom/mongodb-s390x                                                                                   0                    
ibmcom/mongo-c-driver-ppc64le                          Docker image for mongo-c-driver-ppc64leDocke…   0                    
rancher/mongodb-config                                                                                 0                    
mongodb/mongodb-atlas-kubernetes-operator                                                              0                    
mongodb/mongodb-atlas-kubernetes-operator-prerelease   This is a MongoDB Atlas Operator image built…   0                    
[root@k8s101 ~]# docker pull mongo
Using default tag: latest
latest: Pulling from library/mongo
7c3b88808835: Pull complete 
48a403577c28: Pull complete 
76bbb7dc9013: Pull complete 
e81b1e5a386b: Pull complete 
7bdc1db49ec9: Pull complete 
7b2f602f894c: Pull complete 
627a84bea5f4: Pull complete 
fc06fa2a9f52: Pull complete 
0133c89ee92b: Pull complete 
4e990167b745: Pull complete 
Digest: sha256:03ef0031c1642df26d9d3efa9d57e24929672e1ae7aba5818227752089adde36
Status: Downloaded newer image for mongo:latest
docker.io/library/mongo:latest
[root@k8s101 ~]# docker run -p 27017:27017 -d mongo:latest
44a8d8b4a29d38925b5a25da8ae1e9a92f37e18ea1a2ba4ca1ad06ca00e8b501
[root@k8s101 ~]# docker exec -it 44a8d8b4a /bin/bash
root@44a8d8b4a29d:/# mongo
MongoDB shell version v5.0.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("1a4f4b84-0717-48f9-b78a-90dd39c9d50a") }
MongoDB server version: 5.0.6
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
...
mongo基本命令
# mongodb-shell
## 插入测试数据
> db.students.insert({"name": "Bob", "age": 22})
> db.students.insert({"name": "Aollen", "age": 21})
> db.students.insert({"name": "tom", "age": 20})

## 查看有哪些数据
> db.students.find()
{ "_id" : ObjectId("5a1632029d83b8def7401005"), "name" : "Bob", "age" : 22 }
{ "_id" : ObjectId("5a16c89f4da8732f195b4000"), "name" : "Aollen", "age" : 21 }
{ "_id" : ObjectId("5a16c8b74da8732f195b4001"), "name" : "tom", "age" : 20 }
## 查看所有
> db.students.find()
{ "_id" : ObjectId("5a1632029d83b8def7401005"), "name" : "Bob", "age" : 22 }
## 查看指定某个
> db.students.find({"name": "Bob"});
{ "_id" : ObjectId("5a1632029d83b8def7401005"), "name" : "Bob", "age" : 22 }
## 查看指定对象的指定字段(注意 1:代表要展现该字段, 0: 代表不展现该字段, 默认"_id"为要展示)
> db.students.find({"name": "Bob"}, {"age": 1, "_id": 0});
{ "age" : 22 }

# 更新指定对象
> db.students.update({"name": "Bob"}, {$set:{"age": 32}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 按条件更新匹配到的第一条(SQL Where)
> db.students.update({"age": {$gt: 20}}, {$set:{"age": 30}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 按条件更新匹配到的所有(SQL Where)
> db.students.update({"age": {$gt: 20}}, {$set:{"age": 30}}, false, true)
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })

# 删除指定的对象
> db.students.remove({"name": "Bob"})
WriteResult({ "nRemoved" : 1 })
# 删除该collection里面的所有对象
> db.students.remove({})
WriteResult({ "nRemoved" : 2 })
GO基本连接测试
package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"log"
)

func main() {
	fmt.Println("mongo连接测试1")
	TestConn1()
	fmt.Println("mongo连接测试2")
	TestConn2()
}

func TestConn1() {
	// 设置客户端连接配置
	clientOptions := options.Client().ApplyURI("mongodb://192.168.168.101:27017")

	// 连接到MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connected to MongoDB!")
}

func TestConn2() {
	session, err := mgo.Dial("mongodb://192.168.168.101:27017/")
	if err != nil {
		panic(err)
	}
	defer session.Close()
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	c := session.DB("test").C("people")
	err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
		&Person{"Cla", "+55 53 8402 8510"})
	if err != nil {
		log.Fatal(err)
	}
	result := Person{}
	err = c.Find(bson.M{"name": "Ale"}).One(&result)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Phone:", result.Phone)
}

type Person struct {
	Name  string
	Phone string
}

GO微服务连接
package main

import (
	"encoding/json"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"log"
	"net/http"
)

func main() {
	session, err := mgo.Dial("192.168.168.101:27017")
	if err != nil {
		panic(err)
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	ensureIndex(session)
	router := httprouter.New()
	router.GET("/books", allBooks(session))
	router.POST("/books", addBook(session))
	router.GET("/books/:isbn", bookByISBN(session))
	router.PUT("/books/:isbn", updateBook(session))
	router.DELETE("/books/:isbn", deleteBook(session))
	http.ListenAndServe("localhost:8080", router)
}

func ErrorWithJSON(w http.ResponseWriter, message string, code int) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(code)
	fmt.Fprintf(w, "{message: %q}", message)
}
func ResponseWithJSON(w http.ResponseWriter, json []byte, code int) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(code)
	w.Write(json)
}

type Book struct {
	ISBN    string   `json:"isbn"`
	Title   string   `json:"title"`
	Authors []string `json:"authors"`
	Price   string   `json:"price"`
}

func ensureIndex(s *mgo.Session) {
	session := s.Copy()
	defer session.Close()
	c := session.DB("store").C("books")
	index := mgo.Index{
		Key:        []string{"isbn"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
	}
	err := c.EnsureIndex(index)
	if err != nil {
		panic(err)
	}
}
func allBooks(s *mgo.Session) func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		session := s.Copy()
		defer session.Close()
		c := session.DB("store").C("books")
		var books []Book
		err := c.Find(bson.M{}).All(&books)
		if err != nil {
			ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
			log.Println("Failed get all books: ", err)
			return
		}
		respBody, err := json.MarshalIndent(books, "", "  ")
		if err != nil {
			log.Fatal(err)
		}
		ResponseWithJSON(w, respBody, http.StatusOK)
	}
}
func addBook(s *mgo.Session) func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		session := s.Copy()
		defer session.Close()
		var book Book
		decoder := json.NewDecoder(r.Body)
		err := decoder.Decode(&book)
		if err != nil {
			ErrorWithJSON(w, "Incorrect body", http.StatusBadRequest)
			return
		}
		c := session.DB("store").C("books")
		err = c.Insert(book)
		if err != nil {
			if mgo.IsDup(err) {
				ErrorWithJSON(w, "Book with this ISBN already exists", http.StatusBadRequest)
				return
			}
			ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
			log.Println("Failed insert book: ", err)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Header().Set("Location", r.URL.Path+"/"+book.ISBN)
		w.WriteHeader(http.StatusCreated)
	}
}
func bookByISBN(s *mgo.Session) func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		session := s.Copy()
		defer session.Close()
		isbn := ps.ByName("isbn")
		c := session.DB("store").C("books")
		var book Book
		err := c.Find(bson.M{"isbn": isbn}).One(&book)
		if err != nil {
			ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
			log.Println("Failed find book: ", err)
			return
		}
		if book.ISBN == "" {
			ErrorWithJSON(w, "Book not found", http.StatusNotFound)
			return
		}
		respBody, err := json.MarshalIndent(book, "", "  ")
		if err != nil {
			log.Fatal(err)
		}
		ResponseWithJSON(w, respBody, http.StatusOK)
	}
}
func updateBook(s *mgo.Session) func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		session := s.Copy()
		defer session.Close()
		isbn := ps.ByName("isbn")
		var book Book
		decoder := json.NewDecoder(r.Body)
		err := decoder.Decode(&book)
		if err != nil {
			ErrorWithJSON(w, "Incorrect body", http.StatusBadRequest)
			return
		}
		c := session.DB("store").C("books")
		err = c.Update(bson.M{"isbn": isbn}, &book)
		if err != nil {
			switch err {
			default:
				ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
				log.Println("Failed update book: ", err)
				return
			case mgo.ErrNotFound:
				ErrorWithJSON(w, "Book not found", http.StatusNotFound)
				return
			}
		}
		w.WriteHeader(http.StatusNoContent)
	}
}
func deleteBook(s *mgo.Session) func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		session := s.Copy()
		defer session.Close()
		isbn := ps.ByName("isbn")
		c := session.DB("store").C("books")
		err := c.Remove(bson.M{"isbn": isbn})
		if err != nil {
			switch err {
			default:
				ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
				log.Println("Failed delete book: ", err)
				return
			case mgo.ErrNotFound:
				ErrorWithJSON(w, "Book not found", http.StatusNotFound)
				return
			}
		}
		w.WriteHeader(http.StatusNoContent)
	}
}

  • go微服务连接测试
# 微服务测试
# 创建一本book
curl -X POST http://localhost:8080/books -H 'content-type: application/json' -d '{"isbn": "aabbxx", "title": "test titile", "authors":["bob", "aollen"], "price": "100"}'
# 查看创建的book列表
curl -X GET http://localhost:8080/books
[
  {
    "isbn": "aabbxx",
    "title": "test titile",
    "authors": [
      "bob",
      "aollen"
    ],
    "price": "100"
  }
]
# 查看指定的book
curl -X GET http://localhost:8080/books/aabbxx
{
  "isbn": "aabbxx",
  "title": "test titile",
  "authors": [
    "bob",
    "aollen"
  ],
  "price": "100"
}
# 更新指定的book
curl -X PUT http://localhost:8080/books/aabbxx -H 'content-type: application/json' -d '{"isbn": "aabbxx", "price": "99"}'
# 删除指定的book
curl -X DELETE http://localhost:8080/books/aabbxx
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/903422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号