How to query MongoDB database in Golang

PHPz
Release: 2023-04-13 10:05:24
Original
903 people have browsed it

In recent years, Golang has been increasingly used in the development field. As a very popular document database, MongoDB is very convenient to query, add, update, and delete data quickly and easily through Golang without the need for cumbersome SQL statements. This article will introduce how to use Golang to query the MongoDB database.

1. Install MongoDB

Before using MongoDB, you need to install MongoDB first. Download and install it from the official website. After successful installation, you can start the MongoDB service locally. For details, please refer to the official documentation.

2. Install the MongoDB driver

Golang does not officially provide a MongoDB driver. You can use the officially recommended third-party library "mongo-go-driver". Execute the following command in the terminal to install:

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

3. Connect to MongoDB

Before using Golang to operate MongoDB, you need to establish a MongoDB client connection. You can refer to the following sample code:

import (
  "context"
  "fmt"
  "go.mongodb.org/mongo-driver/mongo"
  "go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
  // 配置客户端
  clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

  // 连接 MongoDB
  client, err := mongo.Connect(context.Background(), clientOptions)
  if err != nil {
    fmt.Println("MongoDB Connect Error:", err)
    return
  }

  // 关闭连接
  defer func() {
    if err = client.Disconnect(context.Background()); err != nil {
      panic(err)
    }
  }()
}
Copy after login

4. Query MongoDB data

After the connection is successful, you can start querying the data in the MongoDB database.

  1. Query a single document
collection := client.Database("mydb").Collection("mycollection")
filter := bson.M{"name": "张三"}

var result bson.M
if err = collection.FindOne(context.Background(), filter).Decode(&result); err != nil {
  return
}
Copy after login

Query a single document with specified conditions through the FindOne() method. The parameter filter is the query condition. In this example, query The condition is {"name":"Zhang San"}. The execution result will save the document result in the variable result and return an error message.

  1. Query multiple documents
collection := client.Database("mydb").Collection("mycollection")
filter := bson.M{"age": bson.M{"$gte":18}}

cursor, err := collection.Find(context.Background(), filter)
if err != nil {
  return
}

var results []bson.M
if err = cursor.All(context.Background(), &results); err != nil {
  return
}
Copy after login

Query multiple documents with specified conditions through the Find() method, the parameter filter is the query condition, in this example The query condition is {"age": {"$gte":18}}, which means querying all documents whose age is greater than or equal to 18 years old. The execution result will save all document results in the variable results and return a cursor object.

  1. Get a single document
collection := client.Database("mydb").Collection("mycollection")
filter := bson.M{"name": "张三"}

var result bson.M
if err = collection.FindOne(context.Background(), filter).Decode(&result); err != nil {
  return
}

age := result["age"].(int)
Copy after login

The result of the query is of type bson.M. If you want to get a certain field in it, you should first convert it to its corresponding Use after type.

The above example code only briefly introduces how to use Golang to query the MongoDB database. There are many ways to use MongoDB. You can check the official MongoDB documentation for more details. At the same time, Golang is based on its efficient concurrent processing capabilities. Students who like Golang can try to use Golang and MongoDB to build a high-performance distributed database system.

The above is the detailed content of How to query MongoDB database in Golang. 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