[Go] Go中使用MongoDB

一、安装MongoDB

MonggoDB的官网安装方法目前并没有docker的使用方法,但是在Docker hub却有官方制作的镜像让人迷惑不解。
在以下两个网站中:

个人使用docker启动MongoDB作为测试环境使用,环境如下:

  • Centos7
  • Docker Engine 18.09.7
[root@VM-0-15-centos go-src]# docker run -d --network host mongo:latest
374c814251462e1a31bca8cd5b4108ee5dfebbf2eb9b9fa2f196787ce52e87f1

此时,若是本地没有mongodb的镜像会从docker hub拉下来,就算是安装成功了。

二、使用Mongosh连接

[root@VM-0-15-centos go-src]# docker run -it --network host mongo mongo test
MongoDB shell version v5.0.1
connecting to: mongodb://127.0.0.1:27017/test?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("39cc82f1-8822-4d76-80b9-eedf9f14164d") }
MongoDB server version: 5.0.1
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
	https://community.mongodb.com
>

这样会新启动一个容器,并使用其中的Mongosh来连接刚才容器中的MongoDB。

注意两者必须采用host的docker网络模式,如果不写采用默认bridge,则需要其他措施使其连接上。参见官方文档:https://docs.docker.com/network/host/

三、Mongosh的基本命令

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use test
switched to db test
> db
test
> db.dropDatabase()
{ "ok" : 1 }
> db.createCollection("students")
{ "ok" : 1 }
> show collections
students
> db.student.drop()
false
> db.students.drop()
true
> db.student.insertOne({name:"小王子",age:18});
{
	"acknowledged" : true,
	"insertedId" : ObjectId("60fee869ea53b11353473119")
}
> db.student.insertMany([
... ... {name:"张三",age:20},
... ... {name:"李四",age:25}
... ... ]);
{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("60fee86fea53b1135347311a"),
		ObjectId("60fee86fea53b1135347311b")
	]
}
> db.student.find();
{ "_id" : ObjectId("60fee869ea53b11353473119"), "name" : "小王子", "age" : 18 }
{ "_id" : ObjectId("60fee86fea53b1135347311a"), "name" : "张三", "age" : 20 }
{ "_id" : ObjectId("60fee86fea53b1135347311b"), "name" : "李四", "age" : 25 }
> db.student.find(
... ... {age:{$gt:20}}
... ... )
{ "_id" : ObjectId("60fee86fea53b1135347311b"), "name" : "李四", "age" : 25 }
> db.student.update(
... ... {name:"小王子"},
... ... {name:"老王子",age:98}
... ... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.deleteOne({name:"李四"});
{ "acknowledged" : true, "deletedCount" : 1 }

四、MongoDB Go中的使用

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Student struct {
	Name string
	Age  int
}

func main() {
	// 设置客户端连接配置
	clientOptions := options.Client().ApplyURI("mongodb://localhost: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!")

	// 指定获取要操作的数据集
	collection := client.Database("test").Collection("student")

	// 插入文档
	if false {
		s1 := Student{"小红", 12}
		s2 := Student{"小兰", 10}
		s3 := Student{"小黄", 11}
		// 插入一条文档记录
		insertResult, err := collection.InsertOne(context.TODO(), s1)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("Inserted a single document: ", insertResult.InsertedID)
		// 插入多条文档记录
		students := []interface{}{s2, s3}
		insertManyResult, err := collection.InsertMany(context.TODO(), students)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
	}

	// 更新文档
	if false {
		filter := bson.D{{"name", "小兰"}}
		update := bson.D{
			{"$inc", bson.D{
				{"age", 1},
			}},
		}
		updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
	}

	// 查找文档
	if false {
		filter := bson.D{{"name", "小兰"}}
		var result Student
		err = collection.FindOne(context.TODO(), filter).Decode(&result)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Found a single document: %+v\n", result)
	}

	// 查询多个文档
	if false {
		findOptions := options.Find()
		findOptions.SetLimit(2)

		var results []*Student

		// 返回用来遍历的游标cursor
		cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
		if err != nil {
			log.Fatal(err)
		}

		for cur.Next(context.TODO()) {
			var elem Student
			err := cur.Decode(&elem)
			if err != nil {
				log.Fatal(err)
			}
			results = append(results, &elem)
		}
		if err := cur.Err(); err != nil {
			log.Fatal(err)
		}

		cur.Close(context.TODO())
		fmt.Printf("Found multiple documents (array of pointers): %#v\n", results)
	}

	// 删除单个文档
	if true {
		deleteResult1, err := collection.DeleteOne(context.TODO(), bson.D{{"name","小黄"}})
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult1.DeletedCount)
	}

	// 删除所有文档
	if false {
		deleteResult2, err := collection.DeleteMany(context.TODO(), bson.D{{}})
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult2.DeletedCount)
	}

	// 断开连接
	err = client.Disconnect(context.TODO())
	if err != nil {
		log.Fatal(err)
	}
}

posted @ 2021-07-27 00:55  herrhu  阅读(150)  评论(0编辑  收藏  举报