1// Copyright (C) MongoDB, Inc. 2017-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 7package mongo_test 8 9import ( 10 "context" 11 "fmt" 12 "log" 13 14 "go.mongodb.org/mongo-driver/bson" 15 "go.mongodb.org/mongo-driver/mongo" 16 "go.mongodb.org/mongo-driver/mongo/options" 17 "go.mongodb.org/mongo-driver/mongo/readpref" 18) 19 20func ExampleClient() { 21 // Create a Client and execute a ListDatabases operation. 22 23 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017")) 24 if err != nil { 25 log.Fatal(err) 26 } 27 defer func() { 28 if err = client.Disconnect(context.TODO()); err != nil { 29 log.Fatal(err) 30 } 31 }() 32 33 collection := client.Database("db").Collection("coll") 34 result, err := collection.InsertOne(context.TODO(), bson.D{{"x", 1}}) 35 if err != nil { 36 log.Fatal(err) 37 } 38 fmt.Printf("inserted ID: %v\n", result.InsertedID) 39} 40 41func ExampleConnect_ping() { 42 // Create a Client to a MongoDB server and use Ping to verify that the server is running. 43 44 clientOpts := options.Client().ApplyURI("mongodb://localhost:27017") 45 client, err := mongo.Connect(context.TODO(), clientOpts) 46 if err != nil { 47 log.Fatal(err) 48 } 49 defer func() { 50 if err = client.Disconnect(context.TODO()); err != nil { 51 log.Fatal(err) 52 } 53 }() 54 55 // Call Ping to verify that the deployment is up and the Client was configured successfully. 56 // As mentioned in the Ping documentation, this reduces application resiliency as the server may be 57 // temporarily unavailable when Ping is called. 58 if err = client.Ping(context.TODO(), readpref.Primary()); err != nil { 59 log.Fatal(err) 60 } 61} 62 63func ExampleConnect_replicaSet() { 64 // Create and connect a Client to a replica set deployment. 65 // Given this URI, the Go driver will first communicate with localhost:27017 and use the response to discover 66 // any other members in the replica set. 67 // The URI in this example specifies multiple members of the replica set to increase resiliency as one of the 68 // members may be down when the application is started. 69 70 clientOpts := options.Client().ApplyURI("mongodb://localhost:27017,localhost:27018/?replicaSet=replset") 71 client, err := mongo.Connect(context.TODO(), clientOpts) 72 if err != nil { 73 log.Fatal(err) 74 } 75 _ = client 76} 77 78func ExampleConnect_sharded() { 79 // Create and connect a Client to a sharded deployment. 80 // The URI for a sharded deployment should specify the mongos servers that the application wants to send 81 // messages to. 82 83 clientOpts := options.Client().ApplyURI("mongodb://localhost:27017,localhost:27018") 84 client, err := mongo.Connect(context.TODO(), clientOpts) 85 if err != nil { 86 log.Fatal(err) 87 } 88 _ = client 89} 90 91func ExampleConnect_sRV() { 92 // Create and connect a Client using an SRV record. 93 // SRV records allow administrators to configure a single domain to return a list of host names. 94 // The driver will resolve SRV records prefixed with "_mongodb_tcp" and use the returned host names to 95 // build its view of the deployment. 96 // See https://docs.mongodb.com/manual/reference/connection-string/ for more information about SRV. 97 // Full support for SRV records with sharded clusters requires driver version 1.1.0 or higher. 98 99 clientOpts := options.Client().ApplyURI("mongodb+srv://mongodb.example.com") 100 client, err := mongo.Connect(context.TODO(), clientOpts) 101 if err != nil { 102 log.Fatal(err) 103 } 104 _ = client 105} 106 107func ExampleConnect_direct() { 108 // Create a direct connection to a host. The driver will send all requests to that host and will not 109 // automatically discover other hosts in the deployment. 110 111 clientOpts := options.Client().ApplyURI("mongodb://localhost:27017/?connect=direct") 112 client, err := mongo.Connect(context.TODO(), clientOpts) 113 if err != nil { 114 log.Fatal(err) 115 } 116 _ = client 117} 118 119func ExampleConnect_sCRAM() { 120 // Configure a Client with SCRAM authentication (https://docs.mongodb.com/manual/core/security-scram/). 121 // The default authentication database for SCRAM is "admin". This can be configured via the 122 // authSource query parameter in the URI or the AuthSource field in the options.Credential struct. 123 // SCRAM is the default auth mechanism so specifying a mechanism is not required. 124 125 // To configure auth via URI instead of a Credential, use 126 // "mongodb://user:password@localhost:27017". 127 credential := options.Credential{ 128 Username: "user", 129 Password: "password", 130 } 131 clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetAuth(credential) 132 client, err := mongo.Connect(context.TODO(), clientOpts) 133 if err != nil { 134 log.Fatal(err) 135 } 136 _ = client 137} 138 139func ExampleConnect_x509() { 140 // Configure a Client with X509 authentication (https://docs.mongodb.com/manual/core/security-x.509/). 141 142 // X509 can be configured with different sets of options in the connection string: 143 // 1. tlsCAFile (or SslCertificateAuthorityFile): Path to the file with either a single or bundle of certificate 144 // authorities to be considered trusted when making a TLS connection. 145 // 2. tlsCertificateKeyFile (or SslClientCertificateKeyFile): Path to the client certificate file or the client 146 // private key file. In the case that both are needed, the files should be concatenated. 147 148 // The SetAuth client option should also be used. The username field is optional. If it is not specified, it will 149 // be extracted from the certificate key file. The AuthSource is required to be $external. 150 151 caFilePath := "path/to/cafile" 152 certificateKeyFilePath := "path/to/client-certificate" 153 154 // To configure auth via a URI instead of a Credential, append "&authMechanism=MONGODB-X509" to the URI. 155 uri := "mongodb://host:port/?tlsCAFile=%s&tlsCertificateKeyFile=%s" 156 uri = fmt.Sprintf(uri, caFilePath, certificateKeyFilePath) 157 credential := options.Credential{ 158 AuthMechanism: "MONGODB-X509", 159 } 160 clientOpts := options.Client().ApplyURI(uri).SetAuth(credential) 161 162 client, err := mongo.Connect(context.TODO(), clientOpts) 163 if err != nil { 164 log.Fatal(err) 165 } 166 _ = client 167} 168 169func ExampleConnect_pLAIN() { 170 // Configure a Client with LDAP authentication 171 // (https://docs.mongodb.com/manual/core/authentication-mechanisms-enterprise/#security-auth-ldap). 172 // MongoDB Enterprise supports proxy authentication through an LDAP service that can be used through the PLAIN 173 // authentication mechanism. 174 // This auth mechanism sends the password in plaintext and therefore should only be used with TLS connections. 175 176 // To configure auth via a URI instead of a Credential, use 177 // "mongodb://ldap-user:ldap-pwd@localhost:27017/?authMechanism=PLAIN". 178 credential := options.Credential{ 179 AuthMechanism: "PLAIN", 180 Username: "ldap-user", 181 Password: "ldap-pwd", 182 } 183 clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetAuth(credential) 184 185 client, err := mongo.Connect(context.TODO(), clientOpts) 186 if err != nil { 187 log.Fatal(err) 188 } 189 _ = client 190} 191 192func ExampleConnect_kerberos() { 193 // Configure a Client with GSSAPI/SSPI authentication (https://docs.mongodb.com/manual/core/kerberos/). 194 // MongoDB Enterprise supports proxy authentication through a Kerberos service. 195 // Using Kerberos authentication requires the "gssapi" build tag and cgo support during compilation. 196 // The default service name for Kerberos is "mongodb". This can be configured via the AuthMechanismProperties 197 // field in the options.Credential struct or the authMechanismProperties URI parameter. 198 199 // For Linux, the libkrb5 library is required. 200 // Users can authenticate in one of two ways: 201 // 1. Use an explicit password. In this case, a password must be specified in the URI or the options.Credential 202 // struct and no further setup is required. 203 // 2. Store authentication keys in keytab files. To do this, the kinit binary should be used to initialize a 204 // credential cache for authenticating the user principal. In this example, the invocation would be 205 // "kinit drivers@KERBEROS.EXAMPLE.COM". 206 207 // To configure auth via a URI instead of a Credential, use 208 // "mongodb://drivers%40KERBEROS.EXAMPLE.COM@mongo-server.example.com:27017/?authMechanism=GSSAPI". 209 credential := options.Credential{ 210 AuthMechanism: "GSSAPI", 211 Username: "drivers@KERBEROS.EXAMPLE.COM", 212 } 213 uri := "mongo-server.example.com:27017" 214 clientOpts := options.Client().ApplyURI(uri).SetAuth(credential) 215 216 client, err := mongo.Connect(context.TODO(), clientOpts) 217 if err != nil { 218 log.Fatal(err) 219 } 220 _ = client 221} 222