mgo (gopkg.in/mgo.v2) is no longer maintained. Use the official MongoDB Go Driver instead.go get go.mongodb.org/mongo-driver/mongo
module mongodb-demogo 1.21require go.mongodb.org/mongo-driver v1.13.1
context.Context parameter to control timeouts and cancellation. In production environments, set a reasonable timeout for each operation.url.QueryEscape() to URL-encode the password and prevent special characters from causing parsing errors in the connection string.bson tags. By default, mapped field names are converted to lowercase, so we recommend explicitly specifying the bson tag for each field.mongo.Clienthas a built-in connection pool. Reuse the same instance throughout your application, typically by injecting it as a dependency into your handler functions.Close() on the Cursor returned by Find() after use. We recommend using a defer statement to ensure it is closed properly.package mainimport ("context""fmt""log""net/url""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options""go.mongodb.org/mongo-driver/mongo/readpref")// User defines the user document structure.type User struct {ID primitive.ObjectID `bson:"_id,omitempty"`Username string `bson:"username"`Age int `bson:"age"`Email string `bson:"email"`CreatedAt time.Time `bson:"created_at"`}func main() {// Connection URI (Replace with your actual connection information)// If the password contains special characters, use url.QueryEscape() to encode it.user := "mongouser"password := url.QueryEscape("thepasswordA1")host := "10.66.187.127:27017"uri := fmt.Sprintf("mongodb://%s:%s@%s/admin", user, password, host)// Replica set connection string (Recommended):// uri := fmt.Sprintf("mongodb://%s:%s@IP1:27017,IP2:27017,IP3:27017/admin?replicaSet=cmgo-xxxxxxxx_0", user, password)// Configure connection parametersclientOpts := options.Client().ApplyURI(uri).SetMaxPoolSize(50). // Maximum size of the connection poolSetMinPoolSize(5). // Minimum size of the connection poolSetConnectTimeout(10 * time.Second). // Connection timeoutSetSocketTimeout(30 * time.Second). // Socket timeoutSetMaxConnIdleTime(60 * time.Second). // Idle connection timeoutSetRetryWrites(true). // Enable retryable writesSetRetryReads(true) // Enable retryable reads// Establish a connection.ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()client, err := mongo.Connect(ctx, clientOpts)if err != nil {log.Fatalf("Connection failure: %v", err)}defer func() {if err := client.Disconnect(context.Background()); err != nil {log.Printf("Disconnection failure: %v", err)}fmt.Println("Connection closed")}()// Verify the connectionif err := client.Ping(ctx, readpref.Primary()); err != nil {log.Fatalf("Ping failure: %v", err)}fmt.Println("Connection successful")// Select a database and a collection.collection := client.Database("mydb").Collection("users")// ========== Insert a Document ==========user1 := User{Username: "jack",Age: 31,Email: "jack@example.com",CreatedAt: time.Now(),}insertResult, err := collection.InsertOne(context.Background(), user1)if err != nil {log.Fatalf("Insertion failure: %v", err)}fmt.Printf("Inserted document ID: %v\\n", insertResult.InsertedID)// Batch Insertusers := []interface{}{User{Username: "alice", Age: 28, Email: "alice@example.com", CreatedAt: time.Now()},User{Username: "bob", Age: 35, Email: "bob@example.com", CreatedAt: time.Now()},}insertManyResult, err := collection.InsertMany(context.Background(), users)if err != nil {log.Fatalf("Batch insertion failure: %v", err)}fmt.Printf("Batch inserted %d documents\\n", len(insertManyResult.InsertedIDs))// ========== Query Documents ==========var foundUser Usererr = collection.FindOne(context.Background(), bson.M{"username": "jack"}).Decode(&foundUser)if err != nil {log.Fatalf("Query failure: %v", err)}fmt.Printf("Query a single document: %+v\\n", foundUser)// Conditional Query (Age greater than 30)cursor, err := collection.Find(context.Background(), bson.M{"age": bson.M{"$gt": 30}})if err != nil {log.Fatalf("Conditional query failure: %v", err)}defer cursor.Close(context.Background())fmt.Println("Users with age greater than 30:")for cursor.Next(context.Background()) {var u Userif err := cursor.Decode(&u); err != nil {log.Printf("Decoding failure: %v", err)continue}fmt.Printf(" - %s, Age: %d\\n", u.Username, u.Age)}// ========== Update Documents ==========updateResult, err := collection.UpdateOne(context.Background(),bson.M{"username": "jack"},bson.M{"$set": bson.M{"age": 32}},)if err != nil {log.Fatalf("Update failure: %v", err)}fmt.Printf("Updated %d documents\\n", updateResult.ModifiedCount)// ========== Delete Documents ==========deleteResult, err := collection.DeleteMany(context.Background(),bson.M{"username": bson.M{"$in": bson.A{"jack", "alice", "bob"}}},)if err != nil {log.Fatalf("Deletion failure: %v", err)}fmt.Printf("Deleted %d documents\\n", deleteResult.DeletedCount)}
Connection successfulInserted document ID: ObjectID("6789abcdef1234567890abcd")Batch Insert 2 DocumentsQuery a single document: {ID:ObjectID("6789abcdef1234567890abcd") Username:jack Age:31 Email:jack@example.com CreatedAt:2026-04-17 15:00:00 +0800 CST}Users with age greater than 30:- jack, age: 31- bob, age: 35Update 1 DocumentDelete 3 DocumentsThe connection has been closed.
server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: 10.66.187.127:27017, Type: Unknown, Last error: connection() error occurred during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1" }, ] }
admin in the URI.// Correct: The URI path is /admin.uri := "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin"// Correct: Specify the authentication database via the authSource parameter when connecting to the business database.uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb?authSource=admin"// Error: When connecting to the business database without specifying authSource, the driver defaults to authenticating with the mydb database, causing authentication to fail.uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb"
url.QueryEscape() to encode the password:import "net/url"password := url.QueryEscape("pass@123") // Output: pass%40123uri := fmt.Sprintf("mongodb://mongouser:%s@10.66.187.127:27017/admin", password)
telnet <MongoDB-instance-IP> 27017
Connected indicates that the network is reachable. Check the authentication configuration.Connection timed out indicates that the network is unreachable. Confirm that the CVM and the MongoDB instance are in the same VPC and check the security group rules.context deadline exceeded
SetConnectTimeout configuration is reasonable. In a private network environment, 10 seconds is sufficient:clientOpts := options.Client().ApplyURI(uri).SetConnectTimeout(10 * time.Second)
context timeout for the incoming operation is too short:// Error: Timeout is too short. Complex queries may not be completed within 1 second.ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)// Correct: Set a reasonable timeout based on business complexity.ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()cursor, err := collection.Find(ctx, bson.M{"age": bson.M{"$gt": 30}})
clientOpts := options.Client().ApplyURI(uri).SetMaxConnIdleTime(60 * time.Second). // Idle connections are closed after 60 seconds.SetRetryWrites(true). // Enable retryable writes.SetRetryReads(true) // Enable retryable reads
cannot find module providing package go.mongodb.org/mongo-driver/mongo
go.mod file exists. If it does not exist, execute the following:go mod init <module-name>
go get go.mongodb.org/mongo-driver/mongo
go mod tidy to organize dependencies.go mod tidy
go.mod file contains the following dependencies:require go.mongodb.org/mongo-driver v1.13.1
mgo (gopkg.in/mgo.v2) was discontinued in 2018 and has the following limitations:Comparison Item | mgo (Deprecated) | Official Go Driver |
Maintenance Status | Not supported | Actively maintained |
MongoDB version support | Up to 3.6 | Supports versions 4.0 - 8.0 |
Context support | Not supported | Supported. |
Transaction Support | Not supported | Supported. |
Retryable Reads and Writes | Not supported | Supported. |
Apakah halaman ini membantu?
Anda juga dapat Menghubungi Penjualan atau Mengirimkan Tiket untuk meminta bantuan.
masukan