This question already has an answer here:
- Printing Empty Json as a result [duplicate] 1 answer
- Golang mgo getting empty objects 1 answer
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>