Skip to content

Instantly share code, notes, and snippets.

@cho0h5
Created February 7, 2022 13:29
Show Gist options
  • Save cho0h5/a3f64873b40566c85a78f94acf636815 to your computer and use it in GitHub Desktop.
Save cho0h5/a3f64873b40566c85a78f94acf636815 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
const URI = "mongodb://localhost:27017/"
func main() {
// Connection
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(URI))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
} ()
// Ping
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
panic(err)
}
fmt.Println("Successfully connected and pinged.")
// Insert One
coll := client.Database("test").Collection("books")
doc := bson.D{{"title", "essence of OS"}, {"author", "amuge"}}
result, err := coll.InsertOne(context.TODO(), doc)
fmt.Printf("Inserted document with _id: %v\n", result.InsertedID)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment