...

Source file src/go.mongodb.org/mongo-driver/mongo/readpref/options_example_test.go

Documentation: go.mongodb.org/mongo-driver/mongo/readpref

     1  // Copyright (C) MongoDB, Inc. 2023-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  package readpref_test
     8  
     9  import (
    10  	"context"
    11  
    12  	"go.mongodb.org/mongo-driver/mongo"
    13  	"go.mongodb.org/mongo-driver/mongo/options"
    14  	"go.mongodb.org/mongo-driver/mongo/readpref"
    15  	"go.mongodb.org/mongo-driver/tag"
    16  )
    17  
    18  // Configure a Client with a read preference that selects the nearest replica
    19  // set member that includes tags "region: South" and "datacenter: A".
    20  func ExampleWithTags() {
    21  	rp := readpref.Nearest(
    22  		readpref.WithTags(
    23  			"region", "South",
    24  			"datacenter", "A"))
    25  
    26  	opts := options.Client().
    27  		ApplyURI("mongodb://localhost:27017").
    28  		SetReadPreference(rp)
    29  
    30  	_, err := mongo.Connect(context.Background(), opts)
    31  	if err != nil {
    32  		panic(err)
    33  	}
    34  }
    35  
    36  // Configure a Client with a read preference that selects the nearest replica
    37  // set member matching a set of tags. Try to match members in 3 stages:
    38  //
    39  //  1. Match replica set members that include tags "region: South" and
    40  //     "datacenter: A".
    41  //  2. Match replica set members that includes tag "region: South".
    42  //  3. Match any replica set member.
    43  //
    44  // Stage 3 is used to avoid errors when no members match the previous 2 stages.
    45  func ExampleWithTagSets() {
    46  	tagSetList := tag.NewTagSetsFromMaps([]map[string]string{
    47  		{"region": "South", "datacenter": "A"},
    48  		{"region": "South"},
    49  		{},
    50  	})
    51  
    52  	rp := readpref.Nearest(readpref.WithTagSets(tagSetList...))
    53  
    54  	opts := options.Client().
    55  		ApplyURI("mongodb://localhost").
    56  		SetReadPreference(rp)
    57  
    58  	_, err := mongo.Connect(context.Background(), opts)
    59  	if err != nil {
    60  		panic(err)
    61  	}
    62  }
    63  

View as plain text