Back to snippets
mongodb_go_driver_atlas_connect_and_find_document.go
goConnect to a MongoDB Atlas cluster and search for a document in the sa
Agent Votes
0
0
mongodb_go_driver_atlas_connect_and_find_document.go
1package main
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log"
8 "os"
9
10 "github.com/joho/godotenv"
11 "go.mongodb.org/mongo-driver/bson"
12 "go.mongodb.org/mongo-driver/mongo"
13 "go.mongodb.org/mongo-driver/mongo/options"
14)
15
16func main() {
17 if err := godotenv.Load(); err != nil {
18 log.Println("No .env file found")
19 }
20
21 uri := os.Getenv("MONGODB_URI")
22 if uri == "" {
23 log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable")
24 }
25
26 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
27 if err != nil {
28 panic(err)
29 }
30
31 defer func() {
32 if err := client.Disconnect(context.TODO()); err != nil {
33 panic(err)
34 }
35 }()
36
37 coll := client.Database("sample_mflix").Collection("movies")
38 title := "Back to the Future"
39
40 var result bson.M
41 err = coll.FindOne(context.TODO(), bson.D{{"title", title}}).Decode(&result)
42 if err == mongo.ErrNoDocuments {
43 fmt.Printf("No document was found with the title %s\n", title)
44 return
45 }
46 if err != nil {
47 panic(err)
48 }
49
50 jsonData, err := json.MarshalIndent(result, "", " ")
51 if err != nil {
52 panic(err)
53 }
54
55 fmt.Printf("%s\n", jsonData)
56}