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.
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
This command will download and install the MongoDB Go driver.
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!") }
Code analysis:
clientOptions
, which contains MongoDB The URL of the connection string. In this example, we connect to a locally running MongoDB server. mongo.Connect()
function, passing it the MongoDB connection options clientOptions. This function returns a structure of type mongo.Client. mongo.Client
to ensure that the connection to the database is established and available. 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) } }
Code analysis:
Definition
Use the
Use the mongo.Database
type structure corresponding to the MongoDB database.
Use the
Then, we call the
We use the Book
type structure.
Finally, we use the
Summary 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!