Go MongoDB with mongo-go-driver

beginner
15 min

Go MongoDB with mongo-go-driver

Welcome to our comprehensive guide on working with MongoDB using the mongo-go-driver in Go! This tutorial is designed for both beginners and intermediate learners, so let's get started.

🎯 Understanding the Basics

📝 What is MongoDB?

MongoDB is a popular NoSQL database that uses JSON-like documents with optional schemas. Unlike traditional SQL databases, MongoDB stores data in flexible, JSON-like documents, offering scalability and flexibility.

📝 What is mongo-go-driver?

mongo-go-driver is the official Go language driver for MongoDB. It provides a clean and easy-to-use interface for interacting with MongoDB databases.

🎯 Setting Up Your Environment

Before we dive into the practical part, let's set up our environment:

  1. Install Go: Follow the official Go installation guide.

  2. Install MongoDB: Follow the official MongoDB installation guide.

  3. Install mongo-go-driver: Get the driver from Go's module mirror.

🎯 Connecting to MongoDB

Now, let's write some Go code to connect to our MongoDB instance:

go
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "time" ) func main() { client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { panic(err) } ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) err = client.Connect(ctx) if err != nil { panic(err) } defer client.Disconnect(ctx) fmt.Println("Connected to MongoDB!") }

Run the code above, and you should see "Connected to MongoDB!" printed to the console.

🎯 Creating a Database and Collection

Now that we're connected, let's create a database and a collection:

go
package main // ... (Code from the previous example) func createDatabaseAndCollection(client *mongo.Client) { databaseName := "testDatabase" collectionName := "testCollection" databaseContext := client.Database(databaseName) collection := databaseContext.Collection(collectionName) _, err := collection.InsertOne(context.Background(), map[string]interface{}{"name": "Test Document"}) if err != nil { panic(err) } fmt.Println("Created Database and Collection, and inserted a document.") } func main() { // ... (Code from the previous example) createDatabaseAndCollection(client) }

Run the updated code, and you should see "Created Database and Collection, and inserted a document." printed to the console.

🎯 Reading and Updating Data

Finally, let's read and update data from our collection:

go
package main // ... (Code from the previous examples) func readData(client *mongo.Client) { databaseContext := client.Database("testDatabase") collection := databaseContext.Collection("testCollection") cursor, err := collection.Find(context.Background(), bson.M{}) if err != nil { panic(err) } defer cursor.Close(context.Background()) var result map[string]interface{} if cursor.Next(context.Background()) { cursor.Decode(&result) fmt.Printf("Read document: %+v\n", result) } else { fmt.Println("No documents in collection.") } updateResult, err := collection.UpdateOne(context.Background(), bson.M{"_id": result["_id"}}, bson.D{{"$set", bson.D{{"name", "Updated Test Document"}}}}) if err != nil { panic(err) } fmt.Printf("Updated %d document(s)\n", updateResult.MatchedCount) } func main() { // ... (Code from the previous examples) readData(client) }

Run the updated code, and you should see the document you inserted earlier and the updated document printed to the console.

🎯 Quiz

Quick Quiz
Question 1 of 1

What is MongoDB?

That's it for our introduction to Go MongoDB with mongo-go-driver! Keep practicing and exploring to become proficient in this powerful combination. Happy coding! 😊