Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code file fixes #352

Merged
merged 3 commits into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 8 additions & 47 deletions source/fundamentals/aggregation.txt
Original file line number Diff line number Diff line change
Expand Up @@ -118,32 +118,11 @@ the ``$sum`` expression operator.
.. io-code-block::
:copyable: true

.. input::
.. input:: /includes/fundamentals/code-snippets/aggregation.go
:start-after: begin average
:end-before: end average
:language: go

// create group stage
groupStage := bson.D{
{"$group", bson.D{
{"_id", "$category"},
{"average_price", bson.D{{"$avg", "$price"}}},
{"type_total", bson.D{{"$sum", 1}}},
}}}

// pass the pipeline to the Aggregate() method
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{groupStage})
if err != nil {
panic(err)
}

// display the results
var results []bson.M
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Printf("Average price of %v tea options: $%v \n", result["_id"], result["average_price"])
fmt.Printf("Number of %v tea options: %v \n\n", result["_id"], result["type_total"])
}
:dedent:

.. output::
:language: none
Expand Down Expand Up @@ -171,29 +150,11 @@ The aggregation pipeline contains the following stages:
.. io-code-block::
:copyable: true

.. input::
.. input:: /includes/fundamentals/code-snippets/aggregation.go
:start-after: begin unset
:end-before: end unset
:language: go

// create the stages
matchStage := bson.D{{"$match", bson.D{{"toppings", "milk foam"}}}}
unsetStage := bson.D{{"$unset", bson.A{"_id", "category"}}}
sortStage := bson.D{{"$sort", bson.D{{"price", 1}, {"toppings", 1}}}}
limitStage := bson.D{{"$limit", 2}}

// pass the pipeline to the Aggregate() method
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unsetStage, sortStage, limitStage})
if err != nil {
panic(err)
}

// display the results
var results []Tea
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Printf("Tea: %v \nToppings: %v \nPrice: $%v \n\n", result.Type, strings.Join(result.Toppings, ", "), result.Price)
}
:dedent:

.. output::
:language: none
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ This example performs the following actions:
.. input::
:language: go


filter := bson.D{{"sizes", bson.D{{"$lte", 16}}}}
update := bson.D{{"$inc", bson.D{{"sizes.$", -2}}}}
opts := options.FindOneAndUpdate().
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type Course struct {

func main() {
var uri string
if uri = os.Getenv("DRIVER_REF_URI"); uri == "" {
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ type Book struct {

// end-book-struct

func main() {
insertManyOpts()
insertOneOpts()
}

func insertManyOpts() {
// Sets options to bypass document validation and specify an
// unordered insert when inserting multiple documents
Expand Down
4 changes: 4 additions & 0 deletions source/includes/fundamentals/code-snippets/aggregation.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ func main() {
// Creates a stage to group documents by "category" and
// calculates the average price and total number of documents
// for each "category"
// begin average
groupStage := bson.D{
{"$group", bson.D{
{"_id", "$category"},
Expand All @@ -89,12 +90,14 @@ func main() {
fmt.Printf("Average price of %v tea options: $%v \n", result["_id"], result["average_price"])
fmt.Printf("Number of %v tea options: %v \n\n", result["_id"], result["type_total"])
}
// end average
}

fmt.Println("\nAggregation Example - Unset\n")
{
// Creates stages to match documents, remove the "category"
// field, specify a sort, and limit the output to 2 documents
// begin unset
matchStage := bson.D{{"$match", bson.D{{"toppings", "milk foam"}}}}
unsetStage := bson.D{{"$unset", bson.A{"_id", "category"}}}
sortStage := bson.D{{"$sort", bson.D{{"price", 1}, {"toppings", 1}}}}
Expand All @@ -113,5 +116,6 @@ func main() {
for _, result := range results {
fmt.Printf("Tea: %v \nToppings: %v \nPrice: $%v \n\n", result.Type, strings.Join(result.Toppings, ", "), result.Price)
}
// end unset
}
}
6 changes: 5 additions & 1 deletion source/includes/fundamentals/code-snippets/gridfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"

"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/gridfs"
"go.mongodb.org/mongo-driver/mongo/options"
)

Expand All @@ -22,7 +23,10 @@ func main() {

// Creates a GridFS bucket
db := client.Database("myDB")
bucket := db.GridFSBucket()
bucket, err := gridfs.NewBucket(db)
if err != nil {
panic(err)
}

// begin OpenUploadStream example
file, err := os.Open("home/documents/file.txt")
Expand Down
9 changes: 6 additions & 3 deletions source/includes/fundamentals/code-snippets/srv.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@ package main
import (
"context"
"fmt"
"log"
"os"

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

// Replace the placeholder with your Atlas connection string
const uri = "<connection string>"

func main() {
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/")
}

// Use the SetServerAPIOptions() method to set the Stable API version to 1
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
Expand Down
58 changes: 44 additions & 14 deletions source/includes/fundamentals/code-snippets/timeSeriesRunCommand.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,46 @@
// Creates a command to list collections
command := bson.D{{"listCollections", 1}}
var result bson.M

// Runs the command on the database
commandErr := db.RunCommand(context.TODO(), command).Decode(&result)
if commandErr != nil {
panic(commandErr)
}
package main

import (
"context"
"encoding/json"
"fmt"
"log"
"os"

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

func main() {
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/")
}

client, err := mongo.Connect(options.Client().ApplyURI(uri))

if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())

db := client.Database("myDB")

// Creates a command to list collections
command := bson.D{{"listCollections", 1}}
var result bson.M

// Runs the command on the database
commandErr := db.RunCommand(context.TODO(), command).Decode(&result)
if commandErr != nil {
panic(commandErr)
}

// Prints the command results
output, outputErr := json.MarshalIndent(result, "", " ")
if outputErr != nil {
panic(outputErr)
// Prints the command results
output, outputErr := json.MarshalIndent(result, "", " ")
if outputErr != nil {
panic(outputErr)
}
fmt.Printf("%s\n", output)
}
fmt.Printf("%s\n", output)
Loading