package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" "go.mongodb.org/mongo-driver/mongo/writeconcern" "log" ) func main() { // Create a Client to a MongoDB server and use Ping to verify that the // server is running. clientOpts := options.Client().ApplyURI("mongodb://root:****@dds-bp*******1.mongodb.rds.aliyuncs.com:3717,dds-bp*******2.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-XXXXX") clientOpts.SetReadPreference(readpref.Secondary()) clientOpts.SetWriteConcern(writeconcern.New(writeconcern.WMajority(), writeconcern.J(true), writeconcern.WTimeout(1000))) client, err := mongo.Connect(context.TODO(), clientOpts) if err != nil { fmt.Println("connect failed!") log.Fatal(err) return } fmt.Println("connect successful!") defer func() { if err = client.Disconnect(context.TODO()); err != nil { fmt.Println("disconnect failed!") log.Fatal(err) } fmt.Println("disconnect successful!") }() // Call Ping to verify that the deployment is up and the Client was // configured successfully. As mentioned in the Ping documentation, this // reduces application resiliency as the server may be temporarily // unavailable when Ping is called. if err = client.Ping(context.TODO(), nil); err != nil { fmt.Println("ping failed!") log.Fatal(err) return } fmt.Println("ping successful!") collection := client.Database("baz").Collection("qux") res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"}) if err != nil { fmt.Println("insert result failed!") log.Fatal(err) return } id := res.InsertedID fmt.Println("Id: ", id) fmt.Printf("insert result: %v\n", res) result := bson.M{} filter := bson.D{{"_id", res.InsertedID}} if err := collection.FindOne(context.Background(), filter).Decode(&result); err != nil { fmt.Println("find failed!") log.Fatal(err) return } fmt.Printf("result: %v\n", result) }