📜  mongodb go example (1)

📅  最后修改于: 2023-12-03 15:32:56.540000             🧑  作者: Mango

MongoDB Go Example

This is an example of using MongoDB with Go programming language. MongoDB is a popular NoSQL database that is known for its performance and scalability. Go, on the other hand, is a programming language that is known for its simplicity and speed.

Prerequisites

Before you start, you need to have the following prerequisites:

  • MongoDB installed on your machine
  • Go installed on your machine
  • The MongoDB Go driver installed
Creating A Connection

To start using MongoDB with Go, you need to first create a connection to the MongoDB server. Here is an example of connecting to a local MongoDB server:

package main

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")
    client, err := mongo.Connect(context.Background(), clientOptions)
    if err != nil {
        fmt.Println("Error connecting to MongoDB")
        panic(err)
    }

    err = client.Ping(context.Background(), nil)
    if err != nil {
        fmt.Println("Error pinging MongoDB server")
        panic(err)
    }

    fmt.Println("Connected to MongoDB!")
}

In this code snippet, we are creating a connection to a MongoDB server running on localhost at port 27017.

Inserting Data

To insert data into the MongoDB server from Go, you can use the InsertOne() or InsertMany() functions from the MongoDB Go driver. Here is an example of inserting a single document into a collection:

package main

import (
    "context"
    "fmt"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Person struct {
    Name string `bson:"name"`
    Age  int    `bson:"age"`
}

func main() {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, err := mongo.Connect(context.Background(), clientOptions)
    if err != nil {
        fmt.Println("Error connecting to MongoDB")
        panic(err)
    }
    defer client.Disconnect(context.Background())

    // Get the "people" collection
    collection := client.Database("test").Collection("people")

    // Insert a person
    person := Person{Name: "John Doe", Age: 30}
    insertResult, err := collection.InsertOne(context.Background(), person)
    if err != nil {
        panic(err)
    }
    fmt.Println("Inserted person with ID:", insertResult.InsertedID)
}

In this code snippet, we are inserting a single document of type Person into a collection named people in a database named test.

Querying Data

To query data from the MongoDB server using Go, you can use the Find() function from the MongoDB Go driver. Here is an example of querying all documents from a collection:

package main

import (
    "context"
    "fmt"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Person struct {
    Name string `bson:"name"`
    Age  int    `bson:"age"`
}

func main() {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, err := mongo.Connect(context.Background(), clientOptions)
    if err != nil {
        fmt.Println("Error connecting to MongoDB")
        panic(err)
    }
    defer client.Disconnect(context.Background())

    // Get the "people" collection
    collection := client.Database("test").Collection("people")

    // Query all documents from the collection
    cursor, err := collection.Find(context.Background(), bson.M{})
    if err != nil {
        panic(err)
    }
    defer cursor.Close(context.Background())

    // Iterate through the cursor to print all documents
    for cursor.Next(context.Background()) {
        var person Person
        err := cursor.Decode(&person)
        if err != nil {
            panic(err)
        }
        fmt.Println(person)
    }

    if err := cursor.Err(); err != nil {
        panic(err)
    }
}

In this code snippet, we are querying all documents from a collection named people in a database named test. We are then iterating through the cursor and printing all the documents.

Conclusion

MongoDB is a popular NoSQL database that pairs well with Go programming language. The MongoDB Go driver provides an easy-to-use API for interacting with MongoDB from Go programs. With the examples above, you can start building your own applications using MongoDB and Go!