Skip to content

Instantly share code, notes, and snippets.

@tfogo
Last active June 10, 2019 17:31
Show Gist options
  • Save tfogo/9259cd60b474f64a13b152637ac26533 to your computer and use it in GitHub Desktop.
Save tfogo/9259cd60b474f64a13b152637ac26533 to your computer and use it in GitHub Desktop.

Use Coupon Code GOPHERCON25 for $75 Atlas Credit

cloud.mongodb.com

Getting started with MongoDB and Go

Import the new official MongoDB Go Driver

import (
  "go.mongodb.org/mongo-driver/mongo"
  "go.mongodb.org/mongo-driver/mongo/options"
  "go.mongodb.org/mongo-driver/bson"
)

Create a new client

client, err := mongo.NewClient(
  options.Client().ApplyURI("mongodb://localhost:27017")
)
if err != nil { log.Fatal(err) }

Connect to a database

ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil { log.Fatal(err) }

collection := client.Database("testing").Collection("numbers")

Insert a document

res, err := collection.InsertOne(ctx, bson.M{"value": "Hi"})
if err != nil { log.Fatal(err) }
id := res.InsertedID
fmt.Println("Inserted document: ", id)

Querying for multiple documents returns a cursor

cur, err := collection.Find(ctx, bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(ctx)

for cur.Next(ctx) {
  var result bson.M
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  fmt.Println(result)
}

if err := cur.Err(); err != nil {
  log.Fatal(err)
}

Documentation at godoc.org/go.mongodb.org/mongo-driver

Migration guide for mgo users: mongodb.com/blog/post/go-migration-guide

Get started in under an hour, for free!

Use coupon code GOPHERCON25 for $75 Atlas Credit

cloud.mongodb.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment