Skip to content

GODRIVER-2310 Add snapshot query examples #887

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

Merged
merged 22 commits into from
Mar 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
178 changes: 177 additions & 1 deletion examples/documentation_examples/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/integration/mtest"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
Expand Down Expand Up @@ -2894,7 +2895,7 @@ func StableAPIDeprecationErrorsExample() {
// StableAPIStrictCountExample is an example of using CountDocuments instead of a traditional count
// with a strict stable API since the count command does not belong to API version 1.
func StableAPIStrictCountExample(t *testing.T) {
uri := "mongodb://localhost:27017"
uri := mtest.ClusterURI()

serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1).SetStrict(true)
clientOpts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPIOptions)
Expand Down Expand Up @@ -2956,3 +2957,178 @@ func StableAPIExamples() {
StableAPINonStrictExample()
StableAPIDeprecationErrorsExample()
}

func insertSnapshotQueryTestData(mt *mtest.T) {
catColl := mt.CreateCollection(mtest.Collection{Name: "cats"}, true)
_, err := catColl.InsertMany(context.Background(), []interface{}{
bson.D{
{"adoptable", false},
{"name", "Miyagi"},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is one of these the name of your cat haha

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Miyagi is the name the shelter gave my cat, but I call him Mo :)

{"color", "grey-white"},
{"age", 14},
},
bson.D{
{"adoptable", true},
{"name", "Joyce"},
{"color", "black"},
{"age", 10},
},
})
require.NoError(mt, err)

dogColl := mt.CreateCollection(mtest.Collection{Name: "dogs"}, true)
_, err = dogColl.InsertMany(context.Background(), []interface{}{
bson.D{
{"adoptable", true},
{"name", "Cormac"},
{"color", "rust"},
{"age", 7},
},
bson.D{
{"adoptable", true},
{"name", "Frank"},
{"color", "yellow"},
{"age", 2},
},
})
require.NoError(mt, err)

salesColl := mt.CreateCollection(mtest.Collection{Name: "sales"}, true)
_, err = salesColl.InsertMany(context.Background(), []interface{}{
bson.D{
{"shoeType", "hiking boot"},
{"price", 30.0},
{"saleDate", time.Now()},
},
})
require.NoError(mt, err)
}

func snapshotQueryPetExample(mt *mtest.T) error {
client := mt.Client
db := mt.DB

// Start Snapshot Query Example 1
ctx := context.TODO()

sess, err := client.StartSession(options.Session().SetSnapshot(true))
if err != nil {
return err
}
defer sess.EndSession(ctx)

var adoptablePetsCount int32
err = mongo.WithSession(ctx, sess, func(ctx mongo.SessionContext) error {
// Count the adoptable cats
const adoptableCatsOutput = "adoptableCatsCount"
cursor, err := db.Collection("cats").Aggregate(ctx, mongo.Pipeline{
bson.D{{"$match", bson.D{{"adoptable", true}}}},
bson.D{{"$count", adoptableCatsOutput}},
})
if err != nil {
return err
}
if !cursor.Next(ctx) {
return fmt.Errorf("expected aggregate to return a document, but got none")
}

resp := cursor.Current.Lookup(adoptableCatsOutput)
adoptableCatsCount, ok := resp.Int32OK()
if !ok {
return fmt.Errorf("failed to find int32 field %q in document %v", adoptableCatsOutput, cursor.Current)
}
adoptablePetsCount += adoptableCatsCount

// Count the adoptable dogs
const adoptableDogsOutput = "adoptableDogsCount"
cursor, err = db.Collection("dogs").Aggregate(ctx, mongo.Pipeline{
bson.D{{"$match", bson.D{{"adoptable", true}}}},
bson.D{{"$count", adoptableDogsOutput}},
})
if err != nil {
return err
}
if !cursor.Next(ctx) {
return fmt.Errorf("expected aggregate to return a document, but got none")
}

resp = cursor.Current.Lookup(adoptableDogsOutput)
adoptableDogsCount, ok := resp.Int32OK()
if !ok {
return fmt.Errorf("failed to find int32 field %q in document %v", adoptableDogsOutput, cursor.Current)
}
adoptablePetsCount += adoptableDogsCount
return nil
})
if err != nil {
return err
}
// End Snapshot Query Example 1
require.Equal(mt, int32(3), adoptablePetsCount, "expected 3 total adoptable pets")
return nil
}

func snapshotQueryRetailExample(mt *mtest.T) error {
client := mt.Client
db := mt.DB

// Start Snapshot Query Example 2
ctx := context.TODO()

sess, err := client.StartSession(options.Session().SetSnapshot(true))
if err != nil {
return err
}
defer sess.EndSession(ctx)

var totalDailySales int32
err = mongo.WithSession(ctx, sess, func(ctx mongo.SessionContext) error {
// Count the total daily sales
const totalDailySalesOutput = "totalDailySales"
cursor, err := db.Collection("sales").Aggregate(ctx, mongo.Pipeline{
bson.D{{"$match",
bson.D{{"$expr",
bson.D{{"$gt",
bson.A{"$saleDate",
bson.D{{"$dateSubtract",
bson.D{
{"startDate", "$$NOW"},
{"unit", "day"},
{"amount", 1},
},
}},
},
}},
}},
}},
bson.D{{"$count", totalDailySalesOutput}},
})
if err != nil {
return err
}
if !cursor.Next(ctx) {
return fmt.Errorf("expected aggregate to return a document, but got none")
}

resp := cursor.Current.Lookup(totalDailySalesOutput)

var ok bool
totalDailySales, ok = resp.Int32OK()
if !ok {
return fmt.Errorf("failed to find int32 field %q in document %v", totalDailySalesOutput, cursor.Current)
}
return nil
})
if err != nil {
return err
}
// End Snapshot Query Example 2
require.Equal(mt, int32(1), totalDailySales, "expected 1 total daily sale")
return nil
}

func SnapshotQueryExamples(mt *mtest.T) {
insertSnapshotQueryTestData(mt)
require.NoError(mt, snapshotQueryPetExample(mt))
require.NoError(mt, snapshotQueryRetailExample(mt))
}
80 changes: 60 additions & 20 deletions examples/documentation_examples/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ package documentation_examples_test

import (
"context"
"log"
"os"
"testing"
"time"
Expand All @@ -20,12 +21,23 @@ import (
"go.mongodb.org/mongo-driver/internal/testutil"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/description"
"go.mongodb.org/mongo-driver/mongo/integration/mtest"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/x/bsonx"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
"go.mongodb.org/mongo-driver/x/mongo/driver/topology"
)

func TestMain(m *testing.M) {
if err := mtest.Setup(); err != nil {
log.Fatal(err)
}
defer os.Exit(m.Run())
if err := mtest.Teardown(); err != nil {
log.Fatal(err)
}
}

func TestDocumentationExamples(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
Expand All @@ -37,30 +49,58 @@ func TestDocumentationExamples(t *testing.T) {

db := client.Database("documentation_examples")

documentation_examples.InsertExamples(t, db)
documentation_examples.QueryToplevelFieldsExamples(t, db)
documentation_examples.QueryEmbeddedDocumentsExamples(t, db)
documentation_examples.QueryArraysExamples(t, db)
documentation_examples.QueryArrayEmbeddedDocumentsExamples(t, db)
documentation_examples.QueryNullMissingFieldsExamples(t, db)
documentation_examples.ProjectionExamples(t, db)
documentation_examples.UpdateExamples(t, db)
documentation_examples.DeleteExamples(t, db)
documentation_examples.RunCommandExamples(t, db)
documentation_examples.IndexExamples(t, db)
documentation_examples.StableAPIExamples()
t.Run("InsertExamples", func(t *testing.T) {
documentation_examples.InsertExamples(t, db)
})
t.Run("QueryArraysExamples", func(t *testing.T) {
documentation_examples.QueryArraysExamples(t, db)
})
t.Run("ProjectionExamples", func(t *testing.T) {
documentation_examples.ProjectionExamples(t, db)
})
t.Run("UpdateExamples", func(t *testing.T) {
documentation_examples.UpdateExamples(t, db)
})
t.Run("DeleteExamples", func(t *testing.T) {
documentation_examples.DeleteExamples(t, db)
})
t.Run("RunCommandExamples", func(t *testing.T) {
documentation_examples.RunCommandExamples(t, db)
})
t.Run("IndexExamples", func(t *testing.T) {
documentation_examples.IndexExamples(t, db)
})
t.Run("StableAPExamples", func(t *testing.T) {
documentation_examples.StableAPIExamples()
})
t.Run("QueryToplevelFieldsExamples", func(t *testing.T) {
documentation_examples.QueryToplevelFieldsExamples(t, db)
})
t.Run("QueryEmbeddedDocumentsExamples", func(t *testing.T) {
documentation_examples.QueryEmbeddedDocumentsExamples(t, db)
})
t.Run("QueryArrayEmbeddedDocumentsExamples", func(t *testing.T) {
documentation_examples.QueryArrayEmbeddedDocumentsExamples(t, db)
})
t.Run("QueryNullMissingFieldsExamples", func(t *testing.T) {
documentation_examples.QueryNullMissingFieldsExamples(t, db)
})

mt := mtest.New(t)
defer mt.Close()

// Because it uses RunCommand with an apiVersion, the strict count example can only be
// run on 5.0+ without auth. It also cannot be run on 6.0+ since the count command was
// added to API version 1 and no longer results in an error when strict is enabled.
ver, err := getServerVersion(ctx, client)
require.NoError(t, err, "getServerVersion error: %v", err)
auth := os.Getenv("AUTH") == "auth"
if testutil.CompareVersions(t, ver, "5.0") >= 0 && testutil.CompareVersions(t, ver, "6.0") < 0 && !auth {
documentation_examples.StableAPIStrictCountExample(t)
} else {
t.Log("skipping stable API strict count example")
}
mtOpts := mtest.NewOptions().MinServerVersion("5.0").MaxServerVersion("5.3")
mt.RunOpts("StableAPIStrictCountExample", mtOpts, func(t *mtest.T) {
documentation_examples.StableAPIStrictCountExample(mt.T)
})

mtOpts = mtest.NewOptions().MinServerVersion("5.0").Topologies(mtest.ReplicaSet, mtest.Sharded)
mt.RunOpts("SnapshotQueryExamples", mtOpts, func(t *mtest.T) {
documentation_examples.SnapshotQueryExamples(t)
})
}

func TestAggregationExamples(t *testing.T) {
Expand Down