For this we use the primitive part under bson.
import ( "log" "go.mongodb.org/mongo-driver/bson/primitive" ) type User struct { ID primitive.ObjectID `bson:"_id" json:"id,omitempty"` Email string `json:"email"` }
We are retrieving _id or id fields using ObjectID
.
Let's use it now.
// Connection check clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") client, err := mongo.NewClient(clientOptions) if err != nil { log.Fatal(err) } err = client.Connect(context.Background()) if err != nil { log.Fatal(err) } // Connection check end // Get collection and findOne example object collection := client.Database("example").Collection("users") doc := collection.FindOne(context.TODO(), bson.M{}) // decode user model. var user User doc.Decode(&user) // Print user JSON log.Println(user)
And let's see the result.
{ "id": "5e0fa7c3739e65ceaf6a3020", // yes! "email": "yasaricli@gmail.com" }
Thanks.
Top comments (0)