Skip to content

Instantly share code, notes, and snippets.

@aperezg

aperezg/main.go Secret

Created July 21, 2019 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aperezg/75824db97dd7f81047e32e9fe052954c to your computer and use it in GitHub Desktop.
Save aperezg/75824db97dd7f81047e32e9fe052954c to your computer and use it in GitHub Desktop.
MongoDB driver tutorial
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Starship struct {
ID string `bson:"-"`
Name string `bson:"name"`
Model string `bson:"model"`
CostInCredits int64 `bson:"costInCredits"`
Pilots []Pilot `bson:"pilots"`
}
func main() {
host := "localhost"
port := 27017
clientOpts := options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%d", host, port))
client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
log.Fatal(err)
}
// Check the connections
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Congratulations, you're already connected to MongoDB!")
collection := client.Database("swapi").Collection("starships")
deathStar := Starship{
Name: "Death Star",
Model: "DS-1 Orbital Battle Station",
CostInCredits: 1000000000000,
}
insertResult, err := collection.InsertOne(context.TODO(), deathStar)
if err != nil {
log.Fatal(err)
}
fmt.Println("Death Star had been inserted: ", insertResult.InsertID)
executor := Starship{
Name: "Executor",
Model: "Executor-class star dreadnought",
CostInCredits: 1143350000,
}
millenniumFalcon := Starship{
Name: "Millennium Falcon",
Model: "YT-1300 light freighter",
CostInCredits: 100000,
}
starships := []interface{}{executor, millenniumFalcon}
insertManyResult, err := collection.InsertMany(context.TODO(), starships)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted multiple starships: ", insertManyResult.InsertedIDs)
filter := bson.D{{"name", "Executor"}}
updateResult, err := collectionUpdateOne(context.TODO(), filter, bson.D{
{"$set", bson.D{
{"name", "Executor Black"},
}},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
var result Starship
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Starship found: %v\n", result)
if result.Name != "" {
fmt.Printf("Starship found: %v\n", result)
} else {
fmt.Println("Starship not found")
}
findOpts := options.Find()
findOpts.SetLimit(2)
var results []*Starship
cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
if err != nil {
log.Fatal(err)
}
for cur.Next(context.TODO()) {
// create a value into which the single document can be decoded
var s Starship
err := cur.Decode(&s)
if err != nil {
log.Fatal(err)
}
results = append(results, &s)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
cur.Close(context.TODO())
fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)
deleteResult, err := collection.DeleteOne(context.TODO(), filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Starship deleted", deleteResult.DeletedCount)
err = client.Discconect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Closed connection")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment