Home > Backend Development > Golang > Learn database functions in Go language and implement addition, deletion, modification and query operations of MongoDB data

Learn database functions in Go language and implement addition, deletion, modification and query operations of MongoDB data

王林
Release: 2023-07-29 20:07:53
Original
1254 people have browsed it

Learn the database functions in Go language and implement the addition, deletion, modification and query operations of MongoDB data

Introduction:
Go language is an efficient, concise and easy-to-learn programming language, due to its superior concurrency performance As well as a rich standard library, more and more developers choose to use it to develop various applications. During application development, interaction with the database is a very common requirement. This article will introduce how to use the database functions provided by the Go language, and show how to implement the addition, deletion, modification, and query operations of MongoDB data.

1. Preparation
Before starting, we need to install the MongoDB driver of Go language. You can use the following command to install:

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

2. Connect to the database
First, we need to connect to the MongoDB database in the code. Use the following code example to connect:

package main

import (

"context"
"fmt"
"log"
"time"

"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
Copy after login

)

func main() {

// 设置mongo连接选项
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

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

// 检查连接
err = client.Ping(context.Background(), nil)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")

// 设置超时时间
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

// 关闭连接
err = client.Disconnect(ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Disconnected from MongoDB!")
Copy after login

}

In the above code, we first set the connection options, and then call the mongo.Connect() function to connect to the database. Then use client.Ping() to check whether the connection is successful. Finally, we set the timeout and close the connection to the database using the client.Disconnect() function.

3. Insert data
Below we will learn how to insert data into the MongoDB database. Use the following code example for insertion:

package main

import (

"context"
"fmt"
"log"
"time"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
Copy after login
Copy after login
Copy after login
Copy after login

)

type Person struct {

Name  string
Email string
Copy after login
Copy after login
Copy after login
Copy after login

}

func main() {

// 连接到MongoDB
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
    log.Fatal(err)
}

// 检查连接
err = client.Ping(context.Background(), nil)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")

// 获取集合
collection := client.Database("test").Collection("people")

// 创建一个Person结构体实例
person := Person{Name: "张三", Email: "zhangsan@example.com"}

// 插入一条文档
insertResult, err := collection.InsertOne(context.Background(), person)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Inserted a single document: ", insertResult.InsertedID)

// 设置超时时间
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

// 关闭连接
err = client.Disconnect(ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Disconnected from MongoDB!")
Copy after login

}

In the above code, we created a structure named Person and created it in the main() function A Person structure instance. We then insert the instance into the MongoDB database through the collection.InsertOne() function. After the insertion is successful, print out the inserted document ID.

4. Query data
Next, we will learn how to query data from the MongoDB database. Use the following code example for query operation:

package main

import (

"context"
"fmt"
"log"
"time"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
Copy after login
Copy after login
Copy after login
Copy after login

)

type Person struct {

Name  string
Email string
Copy after login
Copy after login
Copy after login
Copy after login

}

func main() {

// 连接到MongoDB
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
    log.Fatal(err)
}

// 检查连接
err = client.Ping(context.Background(), nil)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")

// 获取集合
collection := client.Database("test").Collection("people")

// 查询一条文档
var result Person
filter := bson.D{{"name", "张三"}}
err = collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Found a single document: ", result)

// 设置超时时间
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

// 关闭连接
err = client.Disconnect(ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Disconnected from MongoDB!")
Copy after login

}

In the above code, we use the collection.FindOne() function to query a document named "Zhang San". The query results are decoded into the result variable and printed.

5. Update data
Below we will learn how to update data in the MongoDB database. Use the following code example for the update operation:

package main

import (

"context"
"fmt"
"log"
"time"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
Copy after login
Copy after login
Copy after login
Copy after login

)

type Person struct {

Name  string
Email string
Copy after login
Copy after login
Copy after login
Copy after login

}

func main() {

// 连接到MongoDB
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
    log.Fatal(err)
}

// 检查连接
err = client.Ping(context.Background(), nil)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")

// 获取集合
collection := client.Database("test").Collection("people")

// 设置更新条件
filter := bson.D{{"name", "张三"}}

// 设置更新内容
update := bson.D{
    {"$set", bson.D{
        {"email", "zhangsan@example.com"},
    }},
}

// 更新一条文档
updateResult, err := collection.UpdateOne(context.Background(), filter, update)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Updated a single document: ", updateResult)

// 设置超时时间
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

// 关闭连接
err = client.Disconnect(ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Disconnected from MongoDB!")
Copy after login

}

In the above code, we use the collection.UpdateOne() function to update the document named "Zhang San" email field. After updating, print out the update results.

6. Delete data
Finally, we will learn how to delete data from the MongoDB database. Use the following code example for deletion:

package main

import (

"context"
"fmt"
"log"
"time"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
Copy after login
Copy after login
Copy after login
Copy after login

)

type Person struct {

Name  string
Email string
Copy after login
Copy after login
Copy after login
Copy after login

}

func main() {

// 连接到MongoDB
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
    log.Fatal(err)
}

// 检查连接
err = client.Ping(context.Background(), nil)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")

// 获取集合
collection := client.Database("test").Collection("people")

// 设置删除条件
filter := bson.D{{"name", "张三"}}

// 删除一条文档
deleteResult, err := collection.DeleteOne(context.Background(), filter)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Deleted a single document: ", deleteResult)

// 设置超时时间
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

// 关闭连接
err = client.Disconnect(ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Disconnected from MongoDB!")
Copy after login

}

In the above code, we use the collection.DeleteOne() function to delete a document named "Zhang San". After deletion, print out the deletion results.

Summary:
This article introduces how to use the database functions in the Go language and implements the addition, deletion, modification and query operations of MongoDB data. By studying this article, we can better understand the combination of Go language and MongoDB. We hope it will be helpful to readers when using Go language for database operations.

The above is the detailed content of Learn database functions in Go language and implement addition, deletion, modification and query operations of MongoDB data. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template