DEV Community

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

Posted on • Edited on

7 3

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay