DEV Community

Yaşar İÇLİ
Yaşar İÇLİ

Posted on • Updated on

Getting mongodb _id for go

For this we use the primitive part under bson.

import (

type User struct {
  ID    primitive.ObjectID `bson:"_id" json:"id,omitempty"`
  Email string             `json:"email"`
Enter fullscreen mode Exit fullscreen mode

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 {

err = client.Connect(context.Background())

if err != nil {

// 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

// Print user JSON
Enter fullscreen mode Exit fullscreen mode

And let's see the result.

  "id": "5e0fa7c3739e65ceaf6a3020", // yes!
  "email": ""
Enter fullscreen mode Exit fullscreen mode


Top comments (0)