MongoDB installation (Docker)
Install a mongo first, and use docker to save trouble.
Docker adds a domestic source address:
"registry-mirrors": [ "." ]
Then pull the mongo image:
docker pull mongodb
Start mongo:
docker run -p 27017:27017 mongo
Install MongoDB Go driver
go get /mongo-driver
Basic code
Create a file and import itbson
,mongo
andmongo/options
Bag.
package main import( "context" "fmt" "log" "/mongo-driver/bson" "/mongo-driver/mongo" "/mongo-driver/mongo/options" ) // This Trainer structure will be used in the following codetype Trainer struct { Name string Age int City string } func main() { // }
Connect to MongoDB using Go Driver
Once the Go driver of MongoDB is imported, we can use itFunctions to connect to MongoDB. You have to pass one
context
andPatient given
Function.Used to set connection configuration.
// Set connection parametersclientOptions := ().ApplyURI("mongodb://localhost:27017") // Connect to MongoDBclient, err := ((), clientOptions) if err != nil { (err) } // Check the connectionerr = ((), nil) if err != nil { (err) } ("Connected to MongoDB!")
Once you have connected to MongoDB, you can now get the trainers collection of the test database.
collection := ("test").Collection("trainers")
The following code will be usedcollection
Come and querytrainers
gather.
If you don't need to query MongoDB, you can use()
To close the MongoDB connection.
err = (()) if err != nil { (err) } ("Connection to MongoDB closed.")
Use BSON objects in Go
It is very necessary to understand how to use BSON objects before sending a query request to MongoDB. The JSON document stored in MongoDB is called BSON and is stored in binary form. Unlike other databases that store JSOn data as strings, BSON also contains field types, which makes it easier for applications to process, sort, and compare reliably. Go's MongoDB driver has two types that represent BSON data: type D and type Raw.
Type D is used to build BSON objects using primitive types in Go. This is especially useful for commands passed to MongoDB. Type D includes four types:
D: A BSON document.
M: Unordered map.
A: A BSON array.
E: Single element inside D.
Here is an example of using the D type to filter documents, where data with names Alice or Bob will be filtered:
({ "name", { {"$in": {"Alice", "Bob"}} } })
CRUD Operation
Once you connect to the database, we can start adding or manipulating the data in the database.Collection
Types have some methods that allow you to send queries to the database.
Insert a document
First, create some new onesTrainer
Structure to insert into the database:
ash := Trainer{"Ash", 10, "Pallet Town"} misty := Trainer{"Misty", 10, "Cerulean City"} brock := Trainer{"Brock", 15, "Pewter" City}
Can be used()
Method to insert a single document:
insertResult, err := ((), ash) if err != nil { (err) } ("Inserted a single document: ", )
If we want to insert multiple documents at once, we can pass a slice tomethod:
trainers := []interface{}{misty, brock} insertManyResult, err := ((), trainers) if err != nil { (err) } ("Inserted multiple documents: ", )
Update the documentation
()
Methods allow you to update a single document. It requires oneType parameters to filter specific documents in the database and then update it.
// Filter records whose name field has a value of Ashfilter := {{"name", "Ash"}} // Update the age field, add 1 valueupdate := { {"$inc", { {"age", 1} }} }
These lines of code add the value of the age field of the document named Ash in the database to 1.
updateResult, err := ((), filter, update) if err != nil { (err) } ("Matched %v documents and updated %v documents.\n", , )
Query Documents
If you want to query a document, you also need to provide a filter document to filter, and you also need a pointer to receive the result. To query a single document, you can use()
method. This method will return a record on the match and parse it to where our pointer points. You can use the same filter as above to query records whose name is Ash.
// Create a variable to receive parsed resultsvar result Trainer err = ((), filter).Decode(&result) if err != nil { (err) } ("Found a single document: %+v\n", result)
If you want to query multiple documents, you can use()
method. This method returns aCursor
(cursor). oneCursor
(cursor) allows us to get one of the records at once. Once a cursor is traversed, you should close the cursor.
In the following example, we also specify some additional options when Finding, here we set the maximum number of records to get to 2.
// This option will be passed to the Find methodfindOptions := () (2) // This is an array used to save the query resultsvar results []*Trainer // Pass {{}} as filter to match all documents in the collectioncur, err := ((), {{}}, findOptions) if err != nil { (err) } // Return a cursor when querying multiple documents// Iterate over this cursor allows us to decode one document at a timefor (()) { // Create a variable to receive a single document var elem Trainer err := (&elem) if err != nil { (err) } results = append(results, &elem) } if err := (); err != nil { (err) } // Once the operation of obtaining data is finished, we need to close cursor(()) ("Found multiple documents (array of pointers): %+v\n", results)
Delete a document
Finally, you can use()
or()
To delete the document. Passed here{ {} }
As a filter parameter, all documents in the collection will be matched. You can also useto delete the entire collection.
deleteResult, err := ((), {{}}) if err != nil { (err) } ("Deleted %v documents in the trainers collection\n", )
Next step
The complete documentation of MongoDB Go driver can be found inView in .
Summarize
This is the end of this article about using MongoDB database in Go. For more information about using MongoDB in Go, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!