Go is an open source programming language that is widely used by many developers. Go also excels at writing efficient and concise queries when interacting with the MongoDB database. This article will introduce how to use MongoDB for querying in Go.
First, we need to install the "mgo" Go-MongoDB driver, which can be installed using the following command:
go get gopkg.in/mgo.v2
After successful installation, we can start to connect to the MongoDB database and perform query operations. The following is the basic MongoDB query code:
package main import ( "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Person struct { Name string Phone string } func main() { session, err := mgo.Dial("localhost:27017") if err != nil { panic(err) } defer session.Close() c := session.DB("test").C("people") result := Person{} err = c.Find(bson.M{"name": "John"}).One(&result) if err != nil { panic(err) } fmt.Println("Phone:", result.Phone) }
In this example, we first create a "Person" structure to represent the attributes of the document to be queried. We use the "mgo.Dial" method to connect to the MongoDB database (in this case the server on localhost) and create a session instance. We then open the "People" collection and perform a query using the "c.Find" method. In this case we are looking for documents with the name "John" and if found we store the result in the "result" variable and print out the phone number.
In addition to basic queries, you can also use some methods and conditional operators to filter and sort queries. The following is an example of a set of common methods and conditional operators:
err = c.Find(bson.M{"age": bson.M{"$lt": 30}}).Sort("-age").Limit(10).All(&results)
This line of code uses the following condition:
You can also use the "Select" method to select the fields to be returned:
err = c.Find(nil).Select(bson.M{"name": 1}).All(&results)
In this example, we only select the "name" field. If we need to exclude a specific field, we can set that field to 0.
err = c.Find(nil).Select(bson.M{"name": 1, "age": 0}).All(&results)
The above is the basic knowledge of using MongoDB for query in Go. Of course, only part of it is covered here. If you want to learn more about MongoDB queries and Go-MongoDB driver, please refer to the relevant materials to learn.
The above is the detailed content of How to use MongoDB for data query in Go. For more information, please follow other related articles on the PHP Chinese website!