All Products
Search
Document Center

ApsaraDB for MongoDB:Connect to a replica set instance by using program code

Last Updated:Apr 23, 2024

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 package of your language. For more information, visit MongoDB Drivers.

Usage notes

If the account password of the replica set instance contains special characters (! @ # $ % ^ & * ( ) _ + =), you must escape these special characters in the connection string. The following table lists mappings between special characters and escaped characters.

Special character

Escape character

!

%21

@

%40

#

%23

$

%24

%

%25

^

%5e

&

%26

*

%2a

(

%28

)

%29

_

%5f

+

%2b

=

%3d

For example, if the original password is ab@#c, the password in the connection string is converted to ab%40%23c.

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. 
    // 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. 
    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. Run the node Node.js command.

Use PHP to connect to a replica set instance

For more information about the PHP Driver for MongoDB, 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. 
    // 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****';
    $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. Run the php -f main.php command.

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.

    // 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. 
            // 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. 
            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. 
    # 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. Run the python3.9 Main.py command.

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. Use the NuGet package management tool in Visual Studio (Project > Manage NuGet Package .) to download 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. 
                // 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. 
                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. 
        // 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. 
        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. Run the go run main.go command.