Created
February 7, 2022 13:29
-
-
Save cho0h5/a3f64873b40566c85a78f94acf636815 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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