Mongo Shell和代码结果返回不同的结果

时间:2019-10-18 03:19:01

标签: mongodb go

我是mongodb的新手,正在尝试遵循一个示例,但是由于它们返回不同的结果,因此无法在mongo shell中检查数据

我的转到代码


    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 You will be using this Trainer type later in the program
    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!")

        collection := client.Database("db_test").Collection("trainers")

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

        trainers := []interface{}{ash, misty, brock}

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

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

        result, err := collection.Find(context.TODO(), bson.D{}, options.Find())

        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Find Failed.")

        for result.Next(context.TODO()) {
            var singleRow Trainer
            err := result.Decode(&singleRow)
            if err != nil {
                log.Fatal(err)
            }

            fmt.Println(singleRow.Name, "+", singleRow.Age)
        }

        fmt.Println("Find finished")

        err = client.Disconnect(context.TODO())

        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Connection to MongoDB closed.")

    }

这将返回


    Connected to MongoDB!
    Inserted a single document:  [ObjectID("5da929e60a2ef8952d92ce8c") ObjectID("5da929e60a2ef8952d92ce8d") ObjectID("5da929e60a2ef8952d92ce8e")]
    Find Failed.
    Ash + 10
    Misty + 10
    Brock + 15
    Find finished
    Connection to MongoDB closed.

mongo shell

1

是因为mongo shell和我的go代码连接到不同的集群或其他东西吗? 我也尝试使用指南针,它显示的结果也不同于mongo shell。我怎么知道外壳正常工作?
我的路径环境设置为“ C:\ Program Files \ MongoDB \ Server \ 4.2 \ bin”,所以我不认为这有问题

1 个答案:

答案 0 :(得分:1)

替换以下行后,尝试运行您的Go代码

clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

与此

clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb")