使用Golang呼叫findOne mongodb时缺少数据

This question already has an answer here:

I'm trying to get data from mongodb to golang program. But I don't know why the received data is not full.

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"
)

func main() {
    ctx := context.Background()
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatal(err)
    }
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")
    db := client.Database("testDB")
    col := db.Collection("testcs")

    type Dataa struct {
        ID        bson.RawValue `bson:"_id"`
        data      string        `bson:"data"`
        number    int           `bson:"number"`
    }
    filter := bson.M{"number": 2}
    var p Dataa
    if err := col.FindOne(ctx, filter).Decode(&p); err != nil {
        log.Fatal(err)
    } 
    fmt.Printf("post: %+v
", p)
}

Receiced data is: post: {ID:{"$oid":"5cf64ca8d95df708be0ed503"} data: number:0}

But the "data" value should be "ABCEX" and "number" value should be 2 like what I have addded into mongodb.

Could you guys please help me to find out the problem. Thank you!

</div>
查看全部
doudouba4520
doudouba4520
2019/06/04 18:05
  • mongodb
  • 点赞
  • 收藏
  • 回答
    私信

0个回复