Skip to content

Commit

Permalink
GODRIVER-2816 Add documentation Example for primitive.Regex Usage (#1245
Browse files Browse the repository at this point in the history
)
  • Loading branch information
prestonvasquez authored and matthewdale committed Jun 5, 2023
1 parent d797822 commit cb5ffcf
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions mongo/crud_examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1071,3 +1071,85 @@ func ExampleIndexView_List() {
}
fmt.Println(results)
}

func ExampleCollection_Find_primitiveRegex() {
ctx := context.TODO()
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

// Connect to a mongodb server.
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
panic(err)
}

defer client.Disconnect(ctx)

type Pet struct {
Type string `bson:"type"`
Name string `bson:"name"`
}

// Create a slice of documents to insert. We will lookup a subset of
// these documents using regex.
toInsert := []interface{}{
Pet{Type: "cat", Name: "Mo"},
Pet{Type: "dog", Name: "Loki"},
}

coll := client.Database("test").Collection("test")

if _, err := coll.InsertMany(ctx, toInsert); err != nil {
panic(err)
}

// Create a filter to find a document with key "name" and any value that
// starts with letter "m". Use the "i" option to indicate
// case-insensitivity.
filter := bson.D{{"name", primitive.Regex{Pattern: "^m", Options: "i"}}}

_, err = coll.Find(ctx, filter)
if err != nil {
panic(err)
}
}

func ExampleCollection_Find_regex() {
ctx := context.TODO()
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

// Connect to a mongodb server.
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
panic(err)
}

defer client.Disconnect(ctx)

type Pet struct {
Type string `bson:"type"`
Name string `bson:"name"`
}

// Create a slice of documents to insert. We will lookup a subset of
// these documents using regex.
toInsert := []interface{}{
Pet{Type: "cat", Name: "Mo"},
Pet{Type: "dog", Name: "Loki"},
}

coll := client.Database("test").Collection("test")

if _, err := coll.InsertMany(ctx, toInsert); err != nil {
panic(err)
}

// Create a filter to find a document with key "name" and any value that
// starts with letter "m". Use the "i" option to indicate
// case-insensitivity.
filter := bson.D{{"name", bson.D{{"$regex", "^m"}, {"$options", "i"}}}}

_, err = coll.Find(ctx, filter)
if err != nil {
panic(err)
}
}

0 comments on commit cb5ffcf

Please sign in to comment.