Connect to a replica set instance by using program code

更新时间:
复制 MD 格式

ApsaraDB for MongoDB is fully compatible with the MongoDB protocol. This topic describes the sample code used to connect to a replica set instance in different languages.

Prerequisites

Download and install the official driver for your programming language. For more information, see MongoDB Drivers .

Usage notes

If the password for a database account on your replica set instance contains special characters such as !@#$%^&*()_+=, you must escape them in the connection string. The following table lists the special characters and their corresponding escape characters.

Special character

Escape character

!

%21

@

%40

#

%23

$

%24

%

%25

^

%5e

&

%26

*

%2a

(

%28

)

%29

_

%5f

+

%2b

=

%3d

For example, if the password is ab@#c, you must use ab%40%23c in the connection string.

Use Node.js to connect to a replica set instance

For more information about the Node.js Driver for MongoDB, see MongoDB Node.js Driver.

  1. Run the following command on the client to initialize the project:

    mkdir node-mongodb-demo
    cd node-mongodb-demo
    npm init -y
  2. Run the following command to install the driver package:

    npm install mongodb
  3. Obtain information used to connect to the replica set instance. For more information, see Connect to a replica set instance.

  4. Save the following sample code as Node.js:

    const MongoClient = require('mongodb').MongoClient;
    
    // The database name and collection name. 
    const demoDb = "test";
    const demoColl = "testColl";
    
    // To ensure high availability, we recommend that you use the connection string URI of the replica set instance. 
    // Ensure that the server where the code is executed can be connected to the ApsaraDB for MongoDB instance. 
    // Escape the special charters if the password contains special characters. 
    const url = "mongodb://root:****@dds-2ze043****.mongodb.rds.aliyuncs.com:3717,dds-2ze043****.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-63****"
    
    console.info("url:", url);
    
    // Obtain the MongoClient. 
    const client = new MongoClient(url);
    
    async function run() {
        try {
            // Connect to the instance. 
            await client.connect();
    
            // Obtain the database handle. 
            const database = client.db(demoDb);
    
            // Obtain the collection handle. 
            const collection = database.collection(demoColl);
    
            // Assemble a record. 
            const demoName = "Node For Demo";
            const doc = { "DEMO": demoName, "MESG": "Hello AliCloudDB For MongoDB" };
            console.info("ready insert document: ", doc);
    
            // Insert a record. 
            const result = await collection.insertOne(doc);
            console.log(
                `A document was inserted with the _id: ${result.insertedId}`,
            );
    
            // Read data. 
            const filter = { "DEMO": demoName };
            const findResult = await collection.find(filter);
            await findResult.forEach(console.dir);
          } finally {
              // Close the connection. 
              await client.close();
          }
    }
    run().catch(console.dir);
                            
  5. Runnode main.js.

Use PHP to connect to a replica set instance

For more information about the PHP driver, see MongoDB PHP Driver.

  1. Run the following command to install the driver package:

    $ pecl install mongodb
    
    # Obtain the INI file path of PHP. 
    $ php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"
    
    # Add the following information to the INI file. Skip this step if it already exists. 
    $ extension=mongodb.so
    
    # Create a project directory and access it. 
    $ mkdir php-demo
    $ cd php-demo
    
    # Use the composer to install MongoDB dependencies. If the composer is not installed, you can download it at https://getcomposer.org/download. 
    $ composer require mongodb/mongodb
  2. Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.

  3. Save the following sample code as main.php:

    <?php
    
    require 'vendor/autoload.php'; // include Composer goodies
    
    
    // To ensure high availability, we recommend that you use the connection string URI of the replica set instance. 
    // Ensure that the server where the code is executed can be connected to the ApsaraDB for MongoDB instance. 
    // Escape the special charters if the password contains special characters. 
    $replicaset_url = 'mongodb://root:****@dds-2ze043****.mongodb.rds.aliyuncs.com:3717,dds-2ze043****.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-63****';
    $test_db = 'test';
    $test_coll = 'testColl';
    
    // Create a MongoClient. 
    $client = new MongoDB\Client($replicaset_url);
    $collection = $client->$test_db->$test_coll;
    
    // Insert a record. 
    $result = $collection->insertOne(['name' => 'ApsaraDB for Mongodb', 'desc' => 'Hello, Mongodb']);
    echo "Inserted with Object ID '{$result->getInsertedId()}'", "\n";
    
    // Query the record. 
    $result = $collection->find(['name' => 'ApsaraDB for Mongodb']);
    foreach ($result as $entry) {
        echo $entry->_id, ': ', $entry->name, "\n";
    }
    
    ?>
  4. Runphp -f main.php.

Use Java to connect to a replica set instance

For more information about the Java Driver for MongoDB, see MongoDB Java Driver.

IDE (IntelliJ IDEA and Eclipse IDE) is used in the example. To connect to a replica set instance in an IDE environment, the JDK must be JDK 8 or later.

  1. Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.

  2. Add Maven dependencies.

    <dependencies>
            <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>mongodb-driver-sync</artifactId>
                <version>4.8.0</version>
            </dependency>
        </dependencies>
  3. Use the following Java sample code.

    Note

    The following code shows how to manually configure a MongoDB connection. In a Spring Boot project, add the@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class}) to disable auto-configuration and prevent connection failures that are caused by configuration conflicts.

    // JDK 8 or later. 
    
    import static com.mongodb.client.model.Filters.eq;
    import org.bson.Document;
    import com.mongodb.MongoException;
    import com.mongodb.client.MongoClient;
    import com.mongodb.client.MongoClients;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    import com.mongodb.client.result.InsertOneResult;
    
    public class Main {
        public static void main( String[] args ) {
            // To ensure high availability, we recommend that you use the connection string URI of the replica set instance. 
            // Ensure that the server where the code is executed can be connected to the ApsaraDB for MongoDB instance. 
            // Escape the special charters if the password contains special characters. 
            String uri = "mongodb://root:****@dds-2ze043****.mongodb.rds.aliyuncs.com:3717,dds-2ze043****.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-63****";
            String demoDb = "test";
            String demoColl = "testColl";
    
            try (MongoClient mongoClient = MongoClients.create(uri)) {
                MongoDatabase database = mongoClient.getDatabase(demoDb);
                MongoCollection<Document> collection = database.getCollection(demoColl);
    
                // Insert a record. 
                try {
                    InsertOneResult result = collection.insertOne(new Document()
                            .append("DEMO", "Java for Demo")
                            .append("MESG", "Hello AliCloudDB For MongoDB"));
                    System.out.println("Success!  Inserted document id: " + result.getInsertedId());
                } catch (MongoException me) {
                    System.err.println("Unable to insert due to an error: " + me);
                }
    
                // Query the first record. 
                Document doc = collection.find(eq("DEMO", "Java for Demo")).first();
                System.out.println(doc.toJson());
    
                mongoClient.close();
            }
        }
    }
  4. In the IDE tool, click Run.

Use Python to connect to a replica set instance

For more information about the Python Driver for MongoDB, see MongoDB Python Driver.

Python 3.9 is used in the example.

  1. Install PyMongo.

    pip install pymongo
  2. Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.

  3. Save the following sample code as Main.py:

    # Python 3.9 is used to run the code. 
    
    from pymongo import MongoClient
    
    # To ensure high availability, we recommend that you use the connection string URI of the replica set instance. 
    # Ensure that the server where the code is executed can be connected to the ApsaraDB for MongoDB instance. 
    # Escape the special characters if the password contains special characters. 
    REPLICASET_URL = 'mongodb://root:****@dds-2ze043****.mongodb.rds.aliyuncs.com:3717,dds-2ze043****.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-63****'
    testDb = 'test'
    testColl = 'testColl'
    
    # Obtain the MongoClient. 
    client = MongoClient(REPLICASET_URL)
    
    
    # Insert a record. 
    doc = dict(DEMO="Python for demo", MESG="Hello ApsaraDB For MongoDB")
    doc_id = client.testDb.testColl.insert_one(doc).inserted_id
    print ('doc_id:', doc_id)
    
    
    # Query the record. 
    for d in client.testDb.testColl.find(dict(DEMO="Python for demo")):
        print ('find documents:', d)
    
    client.close()
  4. Runpython3.9 main.py.

Use C# to connect to a replica set instance

For more information about the C# Driver for MongoDB, see MongoDB C# Driver.

IDE (Visual Studio) is used in the example.

  1. In Visual Studio, open the NuGet Package Manager (Project > Manage NuGet Packages) and install the following package:

    MongoDB.Driver
  2. Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.

  3. Use the following C# sample code:

    using MongoDB.Bson;
    using MongoDB.Driver;
    using System;
    using System.Collections.Generic;
    
    namespace Aliyun
    {
        class Program
        {
            static void Main(string[] args)
            {
                // To ensure high availability, we recommend that you use the connection string URI of the replica set instance. 
                // Ensure that the server where the code is executed can be connected to the ApsaraDB for MongoDB instance. 
                // Escape the special charters if the password contains special characters. 
                const string replicaSetUrl = "mongodb://root:****@dds-2ze043****.mongodb.rds.aliyuncs.com:3717,dds-2ze043****.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-63****";
                const string testDb = "test";
                const string testColl = "testColl";
    
                try
                {
    
                    // Connect to the server and obtain the client. 
                    MongoClient client = new MongoClient(replicaSetUrl);
    
    
                    // Obtain a collection. 
                    var database = client.GetDatabase(testDb);
                    var collection = database.GetCollection<BsonDocument>(testColl);
    
                    // Insert a record. 
                    var document = new BsonDocument
                                {
                                    { "name", "Csharp for Mongodb" },
                                    { "desc", "Hello ApsaraDB For MongoDB" }
                                };
                    collection.InsertOne(document);
                    Console.WriteLine("Insert done\n");
    
                    // Query the record. 
                    var cursor = collection.Find(new BsonDocument{ { "name", "Csharp for Mongodb" } }).ToCursor();
                    foreach (var doc in cursor.ToEnumerable())
                    {
                        Console.WriteLine(doc);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("connection failed:" + e.Message);
    
                }
            }
        }
    }
  4. In the IDE tool, click Run.

Use Go to connect to a replica set instance

For more information about the Go Driver for MongoDB, see MongoDB Go Driver.

  1. Run the following command to install the driver package:

    go get go.mongodb.org/mongo-driver
  2. Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.

  3. Save the following sample code as main.go:

    package main
    
    import (
        "context"
        "fmt"
        "go.mongodb.org/mongo-driver/bson"
        "go.mongodb.org/mongo-driver/mongo"
        "go.mongodb.org/mongo-driver/mongo/options"
        "log"
    )
    
    func main() {
        // To ensure high availability, we recommend that you use the connection string URI of the replica set instance. 
        // Ensure that the server where the code is executed can be connected to the ApsaraDB for MongoDB instance. 
        // Escape the special charters if the password contains special characters. 
        replicaSetUrl := "mongodb://root:****@dds-2ze043****.mongodb.rds.aliyuncs.com:3717,dds-2ze043****.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-63****"
        testDb := "test"
        testColl := "testColl"
    
    
        clientOpts := options.Client().ApplyURI(replicaSetUrl)
    
        // Connect to the server and obtain the client. 
        client, err := mongo.Connect(context.TODO(), clientOpts)
        if err != nil {
            fmt.Println("connect failed!")
            log.Fatal(err)
            return
        }
        fmt.Println("connect successful!")
    
        // Close the connection. 
        defer func() {
            if err = client.Disconnect(context.TODO()); err != nil {
                fmt.Println("disconnect failed!")
                log.Fatal(err)
            }
            fmt.Println("disconnect successful!")
        }()
    
        // Ping the server to verify that the connection is successful. 
        if err = client.Ping(context.TODO(), nil); err != nil {
            fmt.Println("ping failed!")
            log.Fatal(err)
            return
        }
        fmt.Println("ping successful!")
    
        // Insert a record. 
        collection := client.Database(testDb).Collection(testColl)
        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)
    
        // Query the record. 
        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)
    }
                            
  4. Rungo run main.go.

FAQ

How do I troubleshoot application connection errors?

You can troubleshoot an error from the following aspects when you connect to an instance by using the program code:

  • Network connectivity. You can use the mongo shell to connect to the instance for the network connectivity testing. For more information, see Connect to a replica set instance by using the mongo shell.

  • Code issues. After you ensure a smooth connection, you can check whether issues occur in your code and runtime environment configuration.

Why does the client send requests to nodes not listed in the connection string?

This behavior is part of the MongoDB client's service discovery feature, which is essential for high availability. This feature allows the client to automatically adapt to changes in the cluster topology, such as a primary node failure, to ensure service continuity. You can append directConnection=true to the connection string to specify that requests are sent only to a single endpoint. For more information, see directConnection.

Example:

When the client endpoint for a five-node instance is configured as mongodb://root:xxx@dds-xxxxx1-pub.mongodb.rds.aliyuncs.com:3717,dds-xxxxx2-pub.mongodb.rds.aliyuncs.com:3717/admin, the client also sends requests to and monitors the status of the remaining two nodes, which are not included in the preceding endpoint: dds-xxxxx3-pub.mongodb.rds.aliyuncs.com:3717,dds-xxxxx4-pub.mongodb.rds.aliyuncs.com:3717.