Connect to a Serverless instance using program code

Updated at:

ApsaraDB for MongoDB is fully compatible with the MongoDB protocol. This topic provides code examples in various programming languages for connecting to a database instance.

Prerequisites

Note When you connect to a Serverless instance, you do not need to specify the replicaSet parameter in the following examples.

Node.js connection example

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

  1. On the client, run the following commands to initialize the project.
    mkdir node-mongodb-demo
    cd node-mongodb-demo
    npm init
  2. Run the following command to install the driver and tool packages.
    npm install mongodb node-uuid sprintf-js
  3. Obtain the connection information of the ApsaraDB for MongoDB Serverless instance.
  4. The following is the Node.js demo code.
    const sprintf = require("sprintf-js").sprintf;
    const MongoClient = require('mongodb').MongoClient;
    const host1 = "dds-**********.mongodb.rds.aliyuncs.com";
    const port1 = 3717;
    const host2 = "dds-**********.mongodb.rds.aliyuncs.com";
    const port2 = 3717;
    // The database account is node-test.
    const username = "node-test";
    const password = "*********";
    const replSetName = "mgset-*********";
    const demoDb = "test";
    const demoColl = "testColl";
    // Use a replica set endpoint to ensure high availability.
    const url = sprintf("mongodb://%s:%s@%s:%d,%s:%d/admin?replicaSet=%s",
            username, password, host1, port1, host2, port2, replSetName);
    console.info("url:", url);
    const client = new MongoClient(url);
    // Get the MongoClient.
    async function run() {
        try {
            // Connect to the instance.
            await client.connect();
            // Get the database handle.
            const database = client.db(demoDb);
            // Get the collection handle.
            const collection = database.collection(demoColl);
            const demoName = "Node For Demo";
            const doc = { "DEMO": demoName, "MESG": "Hello AliCoudDB For MongoDB" };
            console.info("ready insert document: ", doc);
            // Insert data.
            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);

PHP connection example

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

  1. Install the driver and tool packages.
    pecl install mongodb
    echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
    composer require "mongodb/mongodb=^1.0.0"
  2. Obtain the connection information of the ApsaraDB for MongoDB Serverless instance.
  3. The following is the PHP demo code.
    <?php
    require 'vendor/autoload.php'; // include Composer goodies
    # Instance information.
    $demo_seed1 = '**********.mongodb.test.aliyun-inc.com:3717';
    $demo_seed2 = '**********.mongodb.test.aliyun-inc.com:3717';
    $demo_replname = "mgset-**********";
    # The database account is php-test.
    $demo_user = 'php-test';
    $demo_password = '**********';
    $demo_db = 'admin';
    # Construct the MongoDB connection string based on the instance information.
    # mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
    $demo_uri = 'mongodb://' . $demo_user . ':' . $demo_password . '@' .
        $demo_seed1 . ',' . $demo_seed2 . '/' . $demo_db . '?replicaSet=' . $demo_replname;
    $client = new MongoDB\Client($demo_uri);
    $collection = $client->testDb->testColl;
    $result = $collection->insertOne(['name' => 'ApsaraDB for Mongodb', 'desc' => 'Hello, Mongodb']);
    echo "Inserted with Object ID '{$result->getInsertedId()}'", "\n";
    $result = $collection->find(['name' => 'ApsaraDB for Mongodb']);
    foreach ($result as $entry) {
        echo $entry->_id, ': ', $entry->name, "\n";
    }
    ?>

Java connection example

Related links:
  1. Obtain the connection information of the ApsaraDB for MongoDB Serverless instance.
  2. The following is the Java demo code.
    • Maven configuration.
      <dependencies>
          <dependency>
              <groupId>org.mongodb</groupId>
              <artifactId>mongo-java-driver</artifactId>
              <version>4.1.0</version>
          </dependency>
      </dependencies>
    • Java code.
      import java.util.ArrayList;
      import java.util.List;
      import java.util.UUID;
      import org.bson.BsonDocument;
      import org.bson.BsonString;
      import org.bson.Document;
      import com.mongodb.MongoClient;
      import com.mongodb.MongoClientOptions;
      import com.mongodb.MongoClientURI;
      import com.mongodb.MongoCredential;
      import com.mongodb.ServerAddress;
      import com.mongodb.client.MongoCollection;
      import com.mongodb.client.MongoCursor;
      import com.mongodb.client.MongoDatabase;
       public class Main {
              public static ServerAddress seed1 = new ServerAddress("**********.mongodb.tbc3.newtest.rdstest.aliyun-inc.com",
                              27017);
              public static ServerAddress seed2 = new ServerAddress("**********.mongodb.tbc3.newtest.rdstest.aliyun-inc.com",
                              27017);
              public static String username = "demouser";
              public static String password = "**********";
              public static String ReplSetName = "mgset-**********";
              public static String DEFAULT_DB = "admin";
              public static String DEMO_DB = "test";
              public static String DEMO_COLL = "testColl";
               public static MongoClient createMongoDBClient() {
                      // Build a seed list.
                      List<ServerAddress> seedList = new ArrayList<ServerAddress>();
                      seedList.add(seed1);
                      seedList.add(seed2);
                      // Build authentication information.
                      List<MongoCredential> credentials = new ArrayList<MongoCredential>();
                      credentials.add(MongoCredential.createScramSha1Credential(username, DEFAULT_DB,
                                      password.toCharArray()));
                      // Build operation options. Configure options other than requiredReplicaSetName as needed. The default parameters meet the needs of most scenarios.
                      MongoClientOptions options = MongoClientOptions.builder().requiredReplicaSetName(ReplSetName)
                                      .socketTimeout(2000).connectionsPerHost(1).build();
                      return new MongoClient(seedList, credentials, options);
              }
               public static MongoClient createMongoDBClientWithURI() {
                      // Alternatively, initialize using a URI.
                      // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
                      MongoClientURI connectionString = new MongoClientURI("mongodb://" + username + ":" + password + "@"
                                      + seed1 + "," + seed2 + "/" + DEFAULT_DB + "?replicaSet=" + ReplSetName);
                      return new MongoClient(connectionString);
              }
               public static void main(String args[]) {
                      MongoClient client = createMongoDBClient();
                      // or
                      // MongoClient client = createMongoDBClientWithURI();
                      try {
                              // Get the collection handle.
                              MongoDatabase database = client.getDatabase(DEMO_DB);
                              MongoCollection<Document> collection = database.getCollection(DEMO_COLL);
                              // Insert data.
                              Document doc = new Document();
                              String demoname = "JAVA:" + UUID.randomUUID();
                              doc.append("DEMO", demoname);
                              doc.append("MESG", "Hello AliCoudDB For MongoDB");
                              collection.insertOne(doc);
                              System.out.println("insert document: " + doc);
                              // Read data.
                              BsonDocument filter = new BsonDocument();
                              filter.append("DEMO", new BsonString(demoname));
                              MongoCursor<Document> cursor = collection.find(filter).iterator();
                              while (cursor.hasNext()) {
                                      System.out.println("find document: " + cursor.next());
                              }
                      } finally {
                              // Close the client and release resources.
                              client.close();
                      }
                      return;
              }
      }

Python connection example

  1. Install PyMongo.
    pip install pymongo
  2. Obtain the connection information of the ApsaraDB for MongoDB Serverless instance.
  3. The following is the Python demo code.
    import uuid
    from pymongo import MongoClient
    CONN_ADDR1 = '**********.mongodb.****.******.rdstest.aliyun-inc.com:27017'
    CONN_ADDR2 = '**********.mongodb.****.******.rdstest.aliyun-inc.com:27017'
    REPLICAT_SET = 'mgset-**********'
     username = 'demouser'
    password = '********'
     # Get the MongoClient.
    client = MongoClient([CONN_ADDR1, CONN_ADDR2], replicaSet=REPLICAT_SET)
     # Authenticate. The user is granted permissions on the admin database.
    client.admin.authenticate(username, password)
     # Use the testColl collection in the test database as an example. Insert a document and then find it based on the DEMO name.
    demo_name = 'python-' + str(uuid.uuid1())
    print 'demo_name:', demo_name
     doc = dict(DEMO=demo_name, MESG="Hello ApsaraDB For MongoDB")
    doc_id = client.test.testColl.insert(doc)
    print 'doc_id:', doc_id
     for d in client.test.testColl.find(dict(DEMO=demo_name)):
        print 'find documents:', d

C# connection example

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

  1. On the client, install the following driver package.
    mongocsharpdriver.dll
  2. Obtain the connection information of the ApsaraDB for MongoDB Serverless instance.
  3. The following is the C# demo code.
    using MongoDB.Driver;
    using System;
    using System.Collections.Generic;
    
    namespace Aliyun
    {
        class Program
        {
            static void Main(string[] args)
            {
                // MongoDB instance information
                const string host1 = "dds-t4n**************.mongodb.singapore.rds.aliyuncs.com";
                const int port1 = 3717;
                const string host2 = "dds-t4n**************.mongodb.singapore.rds.aliyuncs.com";
                const int port2 = 3717;
                const string replicaSetName = "mgset-300******";
                const string admin = "admin";
                // The database account is c-test.
                const string userName = "c-test";
                const string passwd = "********";
    
                try
                {
                    Console.WriteLine("Start the connection.......");
                    MongoClientSettings settings = new MongoClientSettings();
                    List<MongoServerAddress> servers = new List<MongoServerAddress>();
                    servers.Add(new MongoServerAddress(host1, port1));
                    servers.Add(new MongoServerAddress(host2, port2));
                    settings.Servers = servers;
                    // Set the replica set name.
                    settings.ReplicaSetName = replicaSetName;
                    // Set the timeout period to 3 seconds.
                    settings.ConnectTimeout = new TimeSpan(0, 0, 0, 3, 0);
                    MongoCredential credentials = MongoCredential.CreateCredential(admin, userName, passwd);
                    settings.Credential = credentials;
                    MongoClient client = new MongoClient(settings);
                    var server = client.GetServer();
                    MongoDatabase database = server.GetDatabase("test");
                    var collection = database.GetCollection<User>("test_collection");
                    User user = new User();
                    user.id = "1";
                    user.name = "mongo_test";
                    user.sex = "female";
                    // Insert the user data.
                    collection.Insert(user);
                    // Get a piece of data.
                    User result = collection.FindOne();
                    Console.WriteLine("id:" + result.id + " name:" + result.name + " sex:"+result.sex);
                    Console.WriteLine("Connection successful.........");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Connection error:"+e.Message);
    
                }
            }
        }
        class User
        {
            public string id { set; get; }
            public string name { set; get; }
            public string sex { set; get; }
    
        }
    }

Go connection example

Related link: MongoDB Go Driver.

  1. Install the following driver package.
    go get go.mongodb.org/mongo-driver
  2. Obtain the connection information of the ApsaraDB for MongoDB Serverless instance.
  3. The following is the Go demo code.
    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/readconcern"
        "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.
        // The database account is go-test and it belongs to the admin database.
        clientOpts := options.Client().ApplyURI("mongodb://go-test:****@s-bp1*******.mongodb.rds.aliyuncs.com:3717,s-bp2*******.mongodb.rds.aliyuncs.com:3717/admin")
        clientOpts.SetReadPreference(readpref.PrimaryPreferred())
        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!")
    
        // Specify the DefaultReadConcern option so any transactions started through
        // the session will have read concern majority.
        // The DefaultReadPreference and DefaultWriteConcern options aren't
        // specified so they will be inherited from client and be set to primary
        // and majority, respectively.
        opts := options.Session().SetDefaultReadConcern(readconcern.Majority())
        sess, err := client.StartSession(opts)
        if err != nil {
            fmt.Println("start session failed!")
            log.Fatal(err)
            return
        }
        defer func() {
            sess.EndSession(context.TODO())
            fmt.Println("end session!")
        }()
        fmt.Println("start session successful!")
    
        txnOpts := options.Transaction()
        result, err := sess.WithTransaction(
            context.TODO(),
            func(sessCtx mongo.SessionContext) (interface{}, error) {
                collection := client.Database("baz").Collection("qux")
                res, err := collection.InsertMany(context.Background(), []interface{}{bson.M{"shardkey": 0}, bson.M{"shardkey": 1}, bson.M{"shardkey": 2}})
                if err != nil {
                    fmt.Println("insert result failed!")
                    log.Fatal(err)
                    return nil, err
                }
                id := res.InsertedIDs
                fmt.Println("Ids: ", id)
                fmt.Printf("insert result: %v\n", res)
    
                result := bson.M{}
                filter := bson.D{{"shardkey", 0}}
                if err := collection.FindOne(context.Background(), filter).Decode(&result); err != nil {
                    fmt.Println("find failed!")
                    log.Fatal(err)
                    return nil, err
                }
                return result, err
            },
            txnOpts)
        if err == nil {
            fmt.Printf("result: %v\n", result)
        }
    }