php小编苹果将为你介绍如何在Go语言中使用Atlas连接MongoDB。Atlas是MongoDB官方的云托管服务,提供了可靠的分布式数据库解决方案。通过Atlas,你可以轻松地在Go语言中连接MongoDB,并进行数据的读写操作。下面将为你详细介绍具体的步骤和代码实现,让你更好地掌握在Go语言中使用Atlas连接MongoDB的技巧。跟着小编一起来学习吧!
问题内容
我在连接到 mongodb 时遇到服务器选择超时问题。如有任何帮助,我们将不胜感激。
selection error: server selection timeout, current topology: { type: replicasetnoprimary, servers: [{ addr: ac-pjyudwq-shard-00-01.1bnb2bm.mongodb.net:27017, type: unknown, last error: dial tcp 3.6.207.111:27017: i/o timeout }, { addr: ac-pjyudwq-shard-00-00.1bnb2bm.mongodb.net:27017, type: unknown, last error: dial tcp 3.7.150.83:27017: i/o timeout }, { addr: ac-pjyudwq-shard-00-02.1bnb2bm.mongodb.net:27017, type: unknown, last error: dial tcp 3.7.137.42:27017: i/o timeout }, ] } exit status 1
我用于连接的代码
const MONGOURL = "mongodb+srv://sai:[email protected]/?retryWrites=true&w=majority" var collection *mongo.Collection func init() { fmt.Println("in the init function") var databasename string = "GOAPI" var collectionname string = "Movies" client, err: = mongo.Connect(context.TODO(), options.Client().ApplyURI(MONGOURL)) if err != nil { fmt.Println("unable to get mongo connection ") log.Fatal(err) } collection = ( * mongo.Collection)(client.Database(databasename).Collection(collectionname)) fmt.Println("sucessfully collection is created ") doc: = Movie { Name: "rrr", Watched: false, Rating: 9, Id: "12121" } result, err: = collection.InsertOne(context.Background(), doc) if err != nil { log.Fatal("hey unable to insert one ", err) } fmt.Println("sucessfully added : ", result.InsertedID) // mongo.Connect()`your text` }
解决方法
我在 aws 上托管我的测试 atlas 集群,因此我希望拥有与 aws 流程类似的凭证管理。从 aws 凭证页面:
默认提供程序链按以下顺序查找凭据:
- 环境变量。
- 共享凭据文件。
- 如果您的应用程序在 amazon ec2 实例上运行,则为 amazon ec2 的 iam 角色。
因此,我想为我的 atlas 示例的简单登录实现可验证的环境。下面的代码假设已在命令行中发出以下行
export mongo_pw=''
然后以下程序将验证您的连接
package main import ( "context" "fmt" "os" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) var username = "<username>" var host1 = "<atlas host>" // of the form foo.mongodb.net func main() { ctx := context.TODO() pw, ok := os.LookupEnv("MONGO_PW") if !ok { fmt.Println("error: unable to find MONGO_PW in the environment") os.Exit(1) } mongoURI := fmt.Sprintf("mongodb+srv://%s:%s@%s", username, pw, host1) fmt.Println("connection string is:", mongoURI) // Set client options and connect clientOptions := options.Client().ApplyURI(mongoURI) client, err := mongo.Connect(ctx, clientOptions) if err != nil { fmt.Println(err) os.Exit(1) } err = client.Ping(ctx, nil) if err != nil { fmt.Println(err) os.Exit(1) } fmt.Println("Connected to MongoDB!") }
从这里开始,我原来问题中链接的教程的其余部分将顺利进行。
以上是如何使用atlas在go中连接mongodb?的详细内容。更多信息请关注PHP中文网其他相关文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可维护,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增强ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口进行模拟和测试的原因是:接口允许定义合同而不指定实现方式,使得测试更加隔离和易于维护。1)接口的隐式实现使创建模拟对象变得简单,这些对象在测试中可以替代真实实现。2)使用接口可以轻松地在单元测试中替换服务的真实实现,降低测试复杂性和时间。3)接口提供的灵活性使得可以为不同测试用例更改模拟行为。4)接口有助于从一开始就设计可测试的代码,提高代码的模块化和可维护性。

在Go中,init函数用于包初始化。1)init函数在包初始化时自动调用,适用于初始化全局变量、设置连接和加载配置文件。2)可以有多个init函数,按文件顺序执行。3)使用时需考虑执行顺序、测试难度和性能影响。4)建议减少副作用、使用依赖注入和延迟初始化以优化init函数的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver CS6
视觉化网页开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)