Skip to content

Instantly share code, notes, and snippets.

@ynwd
Created December 21, 2021 23:31
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 ynwd/0d1454fd137ef6f8526f32ee84d35166 to your computer and use it in GitHub Desktop.
Save ynwd/0d1454fd137ef6f8526f32ee84d35166 to your computer and use it in GitHub Desktop.
mongodb
package main
import (
"context"
"encoding/json"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
uri := "mongodb+srv://admin:admin@cluster0.u16np.mongodb.net"
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)
}
}()
coll := client.Database("sample_mflix").Collection("movies")
title := "Back to the Future"
var result bson.M
err = coll.FindOne(context.TODO(), bson.D{{"title", title}}).Decode(&result)
if err == mongo.ErrNoDocuments {
fmt.Printf("No document was found with the title %s\n", title)
return
}
if err != nil {
panic(err)
}
jsonData, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", jsonData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment