Created
December 21, 2021 23:31
-
-
Save ynwd/0d1454fd137ef6f8526f32ee84d35166 to your computer and use it in GitHub Desktop.
mongodb
This file contains 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" | |
"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