Go MongoDB官方数据库驱动之增删改查

Posted gaiheilukamei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go MongoDB官方数据库驱动之增删改查相关的知识,希望对你有一定的参考价值。

package main

import (
    "context"
    "fmt"
    "log"

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

// Trainer type is used for later
type Trainer struct 
    Name string
    Age  int
    City string


func main() 
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil 
        log.Fatal(err)
    

    // Check the connection
    err = client.Ping(context.TODO(), nil)

    if err != nil 
        log.Fatal(err)
    

    fmt.Println("Connected to MongoDB!")

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

    ash := Trainer"Ash", 10, "Pallet Town"
    misty := Trainer"misty", 10, "Cerulean City"
    brock := Trainer"Brock", 15, "Pewter City"

    // Insert
    insertResult, err := collection.InsertOne(context.TODO(), ash)
    if err != nil 
        log.Fatal(err)
    

    fmt.Println("Inserted a single document: ", insertResult.InsertedID)

    trainers := []interfacemisty, brock

    insertManyResult, err := collection.InsertMany(context.TODO(), trainers)
    if err != nil 
        log.Fatal(err)
    

    fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)

    // Update
    filter := bson.D"name", "Ash"

    update := bson.D
        "$inc", bson.D
            "age", 1,
        ,
    

    updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
    if err != nil 
        log.Fatal(err)
    

    fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)

    // Search 
    var result Trainer
    err = collection.FindOne(context.TODO(), filter).Decode(&result)
    if err != nil 
        log.Fatal(err)
    

    fmt.Printf("Found a single document: %+v\n", result)

    findOptions := options.Find()
    findOptions.SetLimit(5)

    var results []*Trainer

    cur, err := collection.Find(context.TODO(), bson.D, findOptions)
    if err != nil 
        log.Fatal(err)
    

    for cur.Next(context.TODO()) 
        var elem Trainer
        err := cur.Decode(&elem)
        if err != nil 
            log.Fatal(err)
        

        results = append(results, &elem)
    

    if err := cur.Err(); err != nil 
        log.Fatal(err)
    

    cur.Close(context.TODO())

    fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)

    // Delete 
    deleteResult, err := collection.DeleteMany(context.TODO(), bson.D)
    if err != nil 
        log.Fatal(err)
    
    fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)

Document

以上是关于Go MongoDB官方数据库驱动之增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Mongodb之增删改查

MongoDb之增删改查

MongoDB一 之增删改查

MongoDB之增删改查全套语法锦囊⭐️初学者福利

SQL Server之增删改操作

Nodejs操作MySQL之增删改查