Home > Backend Development > Golang > golang+query mongo

golang+query mongo

王林
Release: 2023-05-11 09:19:36
Original
866 people have browsed it

In modern web development, the role of the database is becoming more and more important. MongoDB is a popular non-relational database that has become the first choice for many applications with its flexible data model and powerful query performance. This article aims to introduce the process of using Golang to execute MongoDB queries.

  1. Install the MongoDB driver

Before you start using Golang for MongoDB queries, you need to install the corresponding MongoDB driver. Here, we will introduce the MongoDB official driver, which provides rich functions such as connection management, response reading, data encoding, etc.

To install the official MongoDB driver, use the following command:

go get go.mongodb.org/mongo-driver/mongo
Copy after login

This command will download and install the MongoDB Go driver.

  1. Connecting to MongoDB database

Connecting to MongoDB database is the first step to execute a query. In Go, we use the mongo.Connect() function provided by the MongoDB driver to connect to the MongoDB server. The following is sample code to connect to a MongoDB server:

package main

import (
    "context"
    "fmt"
    "log"
    "time"

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

func main() {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

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

    // Ping the primary
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Connected to MongoDB!")
}
Copy after login

Code analysis:

  1. First, we define a variable called clientOptions, which contains MongoDB The URL of the connection string. In this example, we connect to a locally running MongoDB server.
  2. Then, we call the mongo.Connect() function, passing it the MongoDB connection options clientOptions. This function returns a structure of type mongo.Client.
  3. Next, we use the Ping method of mongo.Client to ensure that the connection to the database is established and available.
  4. Finally, if the connection is successful, the "Connected to MongoDB!" message is printed to the console. If the connection fails, an error message is output and the program is terminated.
  5. Execute MongoDB queries

Once the connection to the MongoDB database is established, you can use FindOne(( ), Find() and Aggregate() methods to execute queries. We take the following sample code as an example, which will query the "books" collection in MongoDB and return all documents in it:

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

type Book struct {
    Title  string
    Author string
}

func main() {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

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

    // Get a handle for the "books" collection.
    collection := client.Database("test").Collection("books")

    // Find all books
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    cursor, err := collection.Find(ctx, bson.M{})
    if err != nil {
        log.Fatal(err)
    }
    defer cursor.Close(ctx)

    // Iterate over the cursor and print each book
    for cursor.Next(ctx) {
        var book Book
        err := cursor.Decode(&book)
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("Title: %s, Author: %s
", book.Title, book.Author)
    }

    if err := cursor.Err(); err != nil {
        log.Fatal(err)
    }
}
Copy after login

Code analysis:

Definition
    Book
  1. structure, which contains two fields: book title and author. Use the
  2. mongo.Connect
  3. function to establish a connection with the database. Use the
  4. client.Database
  5. function to open the MongoDB "test" database. This command will return the mongo.Database type structure corresponding to the MongoDB database. Use the
  6. collection
  7. variable to get the handle of the "books" collection. Here we default to "books" already in MongoDB. Then, we call the
  8. collection.Find()
  9. function, which will return a structure of type mongo.Cursor, in which each document is assigned to its own cursor location. We use an empty bson.M object in this example to get all documents. It's important to point out that we also use context to control timeouts and cancellations. We use the
  10. cursor.Next()
  11. function to retrieve the next document and try to convert it into a Book type structure. Finally, we use the
  12. cursor.Err()
  13. function to catch any errors. Summary
  14. In this article, we introduced how to use Golang to write applications that query MongoDB. We used the official MongoDB driver to demonstrate how to connect to the database and execute queries. We also showed how to use a
bson.M

object to represent a MongoDB query and perform a result set traversal. I hope this article can help readers use MongoDB in Golang for application development.

The above is the detailed content of golang+query mongo. 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