DEV Community

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

Posted on • Edited on

Getting mongodb _id for go

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"`
}
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 {
  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)
Enter fullscreen mode Exit fullscreen mode

And let's see the result.

{
  "id": "5e0fa7c3739e65ceaf6a3020", // yes!
  "email": "yasaricli@gmail.com"
}
Enter fullscreen mode Exit fullscreen mode

Thanks.

Top comments (0)