Skip to content

Instantly share code, notes, and snippets.

@tfogo
Created October 24, 2019 13:14
Show Gist options
  • Save tfogo/1b37303e87c63f02bf34d2472171b167 to your computer and use it in GitHub Desktop.
Save tfogo/1b37303e87c63f02bf34d2472171b167 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017/test")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
coll := client.Database("test").Collection("foo")
result, err := coll.InsertOne(context.Background(), bson.M{"my_data": []byte("abcd")})
if err != nil {
log.Fatal(err)
}
var document interface{}
err = coll.FindOne(context.Background(), bson.M{"_id": result.InsertedID}).Decode(&document)
if err != nil {
log.Fatal(err)
}
log.Printf("%+v", document)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment