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

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

// Set client options
clientOptions := options.Client().ApplyURI("mongodb://user:[email protected]: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数据库、集合进行各种操作了!

猜你喜欢

转载自blog.csdn.net/WU2629409421perfect/article/details/110576407