admin 管理员组

文章数量: 1087817

Go——连接设有账户密码的mongo数据库

testdb 数据库设置的账户是user,密码是123456

// Set client options
clientOptions := options.Client().ApplyURI("mongodb://user:123456@127.0.0.1:27017/testdb")// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)if err != nil {log.Printf("connect err: %v", err)return
}// Check the connection
err = client.Ping(context.TODO(), nil)if err != nil {log.Printf("test connect err: %v", err)return
}//get collection's handle
collection := client.Database("testdb").Collection("testcoll")

获得collection句柄之后,就可以对mongo数据库、集合进行各种操作了!

本文标签: Go连接设有账户密码的mongo数据库