doudouba4520 2019-06-04 18:05
浏览 204

使用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>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 安装svn网络有问题怎么办
    • ¥15 Python爬取指定微博话题下的内容,保存为txt
    • ¥15 vue2登录调用后端接口如何实现
    • ¥65 永磁型步进电机PID算法
    • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
    • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
    • ¥15 如何处理复杂数据表格的除法运算
    • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
    • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
    • ¥15 latex怎么处理论文引理引用参考文献