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) } }() }
4. Query MongoDB data
After the connection is successful, you can start querying the data in the MongoDB database.
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 }
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.
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 }
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.
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)
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!