使用 GoLang 从 MongoDB 中读取文档

Reading documents from MongoDB with GoLang

我能够读取文档并将文档写入数据库,但我遇到了一些非常奇怪的行为。

如果搜索名称“jack”,我得到所有文件,而 Mike 我只得到一个文件,但他们是两个。

搜索方法

func findByFirstName(name string)  {
    fmt.Println("looking for - ", name)
    client, ctx, _ := getConnection()
    quickstart := client.Database("ginPlay")
    namesCollection := quickstart.Collection("names")
    var p []person
    nameObject, err := namesCollection.Find(ctx, bson.M {"lastName": bson.D {
        {"$gt", name},
    }})
    if err = nameObject.All(ctx, &p); err != nil {
        panic(err)
    }

    for i := 0; i < len(p); i++ {
        fmt.Println(p[i])
    }
    
}

输出

looking for -  Jack
Connected to MongoDB!
{ObjectID("613b706bf47bc212c3928870") Mike Smith 25 Netflix}
{ObjectID("613b706cf47bc212c3928872") Jack Jill 36 Surfing}
{ObjectID("613b706ef47bc212c3928874") Jack Jill 25 Hiking}
{ObjectID("613b706ff47bc212c3928876") Jack Jill 30 Snowboarding}
looking for -  Mike
Connected to MongoDB!
{ObjectID("613b706bf47bc212c3928870") Mike Smith 25 Netflix}

这是数据库中的内容

r.GET("/addPerson", func(c *gin.Context) {
        c.String(http.StatusOK, "Hello World!")
        p1 := person{Name: "Mike", LastName: "Foo", Age: 36, Hobbies: "Development"}
        p2 := person{Name: "Mike", LastName: "Smith", Age: 25, Hobbies: "Netflix"}
        p3 := person{Name: "Jack", LastName: "Jill", Age: 36, Hobbies: "Surfing"}
        p4 := person{Name: "Jack", LastName: "Jill", Age: 25, Hobbies: "Hiking"}
        p5 := person{Name: "Jack", LastName: "Jill", Age: 30, Hobbies: "Snowboarding"}

        writePerson(p1)
        writePerson(p2)
            writePerson(p3)
            writePerson(p4)
            writePerson(p5)
        })

数据库连接

// GetConnection - Retrieves a client to the DocumentDB
func getConnection() (*mongo.Client, context.Context, context.CancelFunc) {
    username := "foo"
    password := "pass"
    clusterEndpoint := "cluster0.ml6z7m.mongodb.net/db?retryWrites=true&w=majority"

    connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint)

    client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI))
    if err != nil {
        log.Printf("Failed to create client: %v", err)
    }

    ctx, cancel := context.WithTimeout(context.Background(), connectTimeout * time.Second)

    err = client.Connect(ctx)
    if err != nil {
        log.Printf("Failed to connect to cluster: %v", err)
    }

    // Force a connection to verify our connection string
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Printf("Failed to ping cluster: %v", err)
    }

    fmt.Println("Connected to MongoDB!")
    return client, ctx, cancel

}

控制器

r.GET("/mike", func(c *gin.Context) {
    c.String(http.StatusOK, "Mike")
    findByFirstName("Mike")
})
r.GET("/jack", func(c *gin.Context) {
    c.String(http.StatusOK, "Jack")
    findByFirstName("Jack")
})


type person struct {
    ID     primitive.ObjectID `bson:"_id,omitempty"`
    Name string `bson:"name,omitempty"`
    LastName string `bson:"lastName,omitempty"`
    Age int `bson:"age,omitempty"`
    Hobbies string `bson:"hobbies,omitempty"`
}

函数 findByFirstName() 正在按 lastName 搜索并在该字段上执行大于 ($gt) 操作并在发布的代码中给出 name:

nameObject, err := namesCollection.Find(ctx, bson.M {"lastName": bson.D {
        {"$gt", name},
    }})

您可能犯了一个错误,想将 "lastName" 更改为 "name"

仅找到 Mike Smith,因为 Smith > Mike(Mongo 进行二进制字符串比较 - 请参阅 here)。同样,即使 Jack 的输出也是不正确的,原因也是一样的;它也包括 Mike Smith 因为 SmithJill 都大于 Jack 但不是 Foo.