首页 > 解决方案 > Mongo shell 和代码结果返回不同的结果

问题描述

我是 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.

蒙戈壳

1

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

标签: mongodbgo

解决方案


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

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

有了这个

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

推荐阅读