golang mongodb code example

Example: golang mongo fetch doc

import "go.mongodb.org/mongo-driver/mongo"

// Inside a func

// Set up the client

host := fmt.Sprintf("mongodb://%s:%s@%s:%s",
		"username",
		"password",
		"127.0.0.1",
		"27017")
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(host))
if err != nil {
  log.Fatal(err)
}

// Run the query
col := client.Database("database_name").Collection("collection_name")
result := col.FindOne(context.Background(), bson.M{"filter_key":"filter_value"})
if result.Err() == mongo.ErrNoDocuments {
  // return nil
}
// Decode the value into a map or struct containing bson tags. e.g. type S struct { Name string `bson:"firstName"` }
var m map[string]interface{}
if err := result.Decode(&m); err != nil {
  log.Fatal(err)
}
//return m

Tags:

Go Example