下载安装驱动并连接数据库

下载地址https://www.mongodb.com/try/download/community

打开客户端

mongo.exe

创建数据库

use go_db;

创建集合

 db.createCollection("student");

下载驱动https://pkg.go.dev/go.mongodb.org/mongo-driver

go get go.mongodb.org/mongo-driver/mongo

在这里插入图片描述

go连接MongoDB

package main

import (
	"context"
	"fmt"
	"log"

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

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	co := options.Client().ApplyURI("mongodb://localhost:27017")
	// 连接到MongoDB
	var err error
	c, err2 := mongo.Connect(context.TODO(), co)
	if err2 != nil {
		log.Fatal(err2)
	}
	// 检查连接
	err3 := c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err3)
	}
	fmt.Println("mongodb connected")
}

func main() {
	initDB()
}

在这里插入图片描述

添加文档

添加一条文档

package main

import (
	"context"
	"fmt"
	"log"

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

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	co := options.Client().ApplyURI("mongodb://localhost:27017")
	// 连接到MongoDB
	var err error
	c, err2 := mongo.Connect(context.TODO(), co)
	if err2 != nil {
		log.Fatal(err2)
	}
	// 检查连接
	err3 := c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err3)
	}
	fmt.Println("mongodb connected")
	client = c
}

type Student struct {
	Name string
	Age  int
}

func insertOne(s Student) {
	initDB()
	c := client.Database("go_db").Collection("student")
	ior, err := c.InsertOne(context.TODO(), s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("ior.InsertedID: %v\n", ior.InsertedID)
}
func main() {
	s := Student{Name: "wang fan", Age: 26}
	insertOne(s)
}

在这里插入图片描述通过MongoDB可视化工具查看有数据哦!
在这里插入图片描述添加多条文档

package main

import (
	"context"
	"fmt"
	"log"

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

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	co := options.Client().ApplyURI("mongodb://localhost:27017")
	// 连接到MongoDB
	var err error
	c, err2 := mongo.Connect(context.TODO(), co)
	if err2 != nil {
		log.Fatal(err2)
	}
	// 检查连接
	err3 := c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err3)
	}
	fmt.Println("mongodb connected")
	client = c
}

type Student struct {
	Name string
	Age  int
}

func insertOne(s Student) {
	initDB()
	c := client.Database("go_db").Collection("student")
	ior, err := c.InsertOne(context.TODO(), s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("ior.InsertedID: %v\n", ior.InsertedID)
}
func insertMore(students []interface{}) {
	initDB()
	c := client.Database("go_db").Collection("student")
	imr, err := c.InsertMany(context.TODO(), students)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("imr.InsertedIDs: %v\n", imr.InsertedIDs)
}
func main() {
	s1 := Student{Name: "wang fan1", Age: 26}
	s2 := Student{Name: "wang fan2", Age: 26}
	s3 := Student{Name: "wang fan3", Age: 26}
	students := []interface{}{s1, s2, s3}
	insertMore(students)
}

在这里插入图片描述通过MongoDB可视化工具查看有数据哦
在这里插入图片描述

查找文档

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"
)

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	co := options.Client().ApplyURI("mongodb://localhost:27017")
	// 连接到MongoDB
	var err error
	c, err2 := mongo.Connect(context.TODO(), co)
	if err2 != nil {
		log.Fatal(err2)
	}
	// 检查连接
	err3 := c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err3)
	}
	fmt.Println("mongodb connected")
	client = c
}

type Student struct {
	Name string
	Age  int
}

func insertOne(s Student) {
	initDB()
	c := client.Database("go_db").Collection("student")
	ior, err := c.InsertOne(context.TODO(), s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("ior.InsertedID: %v\n", ior.InsertedID)
}
func insertMore(students []interface{}) {
	initDB()
	c := client.Database("go_db").Collection("student")
	imr, err := c.InsertMany(context.TODO(), students)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("imr.InsertedIDs: %v\n", imr.InsertedIDs)
}
func findData() {
	initDB()
	defer client.Disconnect(context.TODO())
	c := client.Database("go_db").Collection("student")
	// c2, _ := c.Find(context.Background(), bson.D{{Key: "name", Value: "wang fan"}})
	// c2, _ := c.Find(context.Background(), bson.D{{"name", "wang fan"}})
	c2, _ := c.Find(context.Background(), bson.D{})
	defer c2.Close(context.Background())
	for c2.Next(context.Background()) {
		var result bson.D
		err := c2.Decode(&result)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("result: %v\n", result)
		fmt.Printf("result.Map(): %v\n", result.Map())
		fmt.Printf("result.Map()[\"name\"]: %v\n", result.Map()["name"])
	}
	if err := c2.Err(); err != nil {
		log.Fatal(err)
	}
}
func main() {
	/* s1 := Student{Name: "wang fan1", Age: 26}
	s2 := Student{Name: "wang fan2", Age: 26}
	s3 := Student{Name: "wang fan3", Age: 26}
	students := []interface{}{s1, s2, s3}
	insertMore(students) */
	findData()
}

注意注释的两行,可打开后进行测试
在这里插入图片描述

更新文档

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"
)

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	co := options.Client().ApplyURI("mongodb://localhost:27017")
	// 连接到MongoDB
	var err error
	c, err2 := mongo.Connect(context.TODO(), co)
	if err2 != nil {
		log.Fatal(err2)
	}
	// 检查连接
	err3 := c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err3)
	}
	fmt.Println("mongodb connected")
	client = c
}

type Student struct {
	Name string
	Age  int
}

func insertOne(s Student) {
	initDB()
	c := client.Database("go_db").Collection("student")
	ior, err := c.InsertOne(context.TODO(), s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("ior.InsertedID: %v\n", ior.InsertedID)
}
func insertMore(students []interface{}) {
	initDB()
	c := client.Database("go_db").Collection("student")
	imr, err := c.InsertMany(context.TODO(), students)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("imr.InsertedIDs: %v\n", imr.InsertedIDs)
}
func findData() {
	initDB()
	defer client.Disconnect(context.TODO())
	c := client.Database("go_db").Collection("student")
	// c2, _ := c.Find(context.Background(), bson.D{{Key: "name", Value: "wang fan"}})
	// c2, _ := c.Find(context.Background(), bson.D{{"name", "wang fan"}})
	c2, _ := c.Find(context.Background(), bson.D{})
	defer c2.Close(context.Background())
	for c2.Next(context.Background()) {
		var result bson.D
		err := c2.Decode(&result)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("result: %v\n", result)
		fmt.Printf("result.Map(): %v\n", result.Map())
		fmt.Printf("result.Map()[\"name\"]: %v\n", result.Map()["name"])
	}
	if err := c2.Err(); err != nil {
		log.Fatal(err)
	}
}
func update() {
	initDB()
	defer client.Disconnect(context.TODO())
	c := client.Database("go_db").Collection("student")
	update := bson.D{{"$set", bson.D{{Key: "name", Value: "王帆"}, {Key: "age", Value: 18}}}}
	// 更新条件 name wang fan 更新问 王帆 年龄 18
	ur, err := c.UpdateMany(context.TODO(), bson.D{{"name", "wang fan"}}, update)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("ur.ModifiedCount: %v\n", ur.ModifiedCount)
}
func main() {
	update()
}

在这里插入图片描述

通过MongoDB可视化工具进行查看
在这里插入图片描述

删除文档

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"
)

var client *mongo.Client

func initDB() {
	// 设置客户端连接配置
	co := options.Client().ApplyURI("mongodb://localhost:27017")
	// 连接到MongoDB
	var err error
	c, err2 := mongo.Connect(context.TODO(), co)
	if err2 != nil {
		log.Fatal(err2)
	}
	// 检查连接
	err3 := c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err3)
	}
	fmt.Println("mongodb connected")
	client = c
}

type Student struct {
	Name string
	Age  int
}

func insertOne(s Student) {
	initDB()
	c := client.Database("go_db").Collection("student")
	ior, err := c.InsertOne(context.TODO(), s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("ior.InsertedID: %v\n", ior.InsertedID)
}
func insertMore(students []interface{}) {
	initDB()
	c := client.Database("go_db").Collection("student")
	imr, err := c.InsertMany(context.TODO(), students)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("imr.InsertedIDs: %v\n", imr.InsertedIDs)
}
func findData() {
	initDB()
	defer client.Disconnect(context.TODO())
	c := client.Database("go_db").Collection("student")
	// c2, _ := c.Find(context.Background(), bson.D{{Key: "name", Value: "wang fan"}})
	// c2, _ := c.Find(context.Background(), bson.D{{"name", "wang fan"}})
	c2, _ := c.Find(context.Background(), bson.D{})
	defer c2.Close(context.Background())
	for c2.Next(context.Background()) {
		var result bson.D
		err := c2.Decode(&result)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("result: %v\n", result)
		fmt.Printf("result.Map(): %v\n", result.Map())
		fmt.Printf("result.Map()[\"name\"]: %v\n", result.Map()["name"])
	}
	if err := c2.Err(); err != nil {
		log.Fatal(err)
	}
}
func update() {
	initDB()
	defer client.Disconnect(context.TODO())
	c := client.Database("go_db").Collection("student")
	update := bson.D{{"$set", bson.D{{Key: "name", Value: "王帆"}, {Key: "age", Value: 18}}}}
	// 更新条件 name wang fan 更新问 王帆 年龄 18
	ur, err := c.UpdateMany(context.TODO(), bson.D{{"name", "wang fan"}}, update)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("ur.ModifiedCount: %v\n", ur.ModifiedCount)
}
func delete() {
	initDB()
	defer client.Disconnect(context.TODO())
	c := client.Database("go_db").Collection("student")
	dr, err := c.DeleteMany(context.TODO(), bson.D{{Key: "name", Value: "王帆"}})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("dr.DeletedCount: %v\n", dr.DeletedCount)
}
func main() {
	delete()
}

在这里插入图片描述查一下MongoDB可视化工具
在这里插入图片描述

一定要看官方文档!!!!

https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#section-documentation

Logo

华为云1024程序员节送福利,参与活动赢单人4000元礼包,更有热门技术干货免费学习

更多推荐