2024-05-15 05:56:21 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2024-05-21 10:21:49 +00:00
|
|
|
"context"
|
2024-05-15 05:56:21 +00:00
|
|
|
"fmt"
|
2024-05-21 10:21:49 +00:00
|
|
|
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
2024-05-15 05:56:21 +00:00
|
|
|
)
|
|
|
|
|
2024-05-21 10:21:49 +00:00
|
|
|
|
2024-05-15 05:56:21 +00:00
|
|
|
func initReplMongo() {
|
2024-05-21 10:21:49 +00:00
|
|
|
// Create a new client and connect to the servers
|
|
|
|
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:30000"))
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
defer client.Disconnect(context.TODO())
|
|
|
|
|
|
|
|
// Get a handle to the admin database
|
|
|
|
admin := client.Database("admin")
|
|
|
|
|
|
|
|
// Define the replica set configuration
|
|
|
|
config := bson.M{
|
|
|
|
"_id": replicasetName,
|
|
|
|
"members": []bson.M{},
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := 0; i < int(numberOfContainers); i++ {
|
|
|
|
member := bson.M{
|
|
|
|
"_id": i,
|
|
|
|
"host": fmt.Sprintf("mongo%d", i),
|
|
|
|
}
|
|
|
|
config["members"] = append(config["members"].([]bson.M), member)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Initiate the replica set
|
|
|
|
res, err := admin.RunCommand(context.TODO(), bson.D{{"replSetInitiate", config}}).Raw()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println(res)
|
2024-05-15 05:56:21 +00:00
|
|
|
}
|