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
Precautions
! @ # $ % ^ & * ( ) _ + =
, you must escape the special characters in the connection string. The following table lists mappings between special characters and escaped character.Special character | Escaped character |
---|---|
! | %21 |
@ | %40 |
# | %23 |
$ | %24 |
% | %25 |
^ | %5e |
& | %26 |
* | %2a |
( | %28 |
) | %29 |
_ | %5f |
+ | %2b |
= | %3d |
For example, if the password is ab@#c
, escaped characters of the password are ab%40%23c
in the connection string.
Node.js
Related link: MongoDB Node.js Driver.
- Run the following commands on the client to initialize a project:
mkdir node-mongodb-demo cd node-mongodb-demo npm init -y
- Run the following command to install the driver package:
npm install mongodb
- Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.
- 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"; // We recommend that you use the connection string URI to ensure high availability. // 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 AliCoudDB 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);
- Run the
node Node.js
command.
PHP
Related link: MongoDB PHP Driver.
- 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
- Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.
- Save the following sample code as main.php:
<?php require 'vendor/autoload.php'; // include Composer goodies // We recommend that you use the connection string URI to ensure high availability. // 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"; } ?>
- Run the
php -f main.php
command.
Java
Related link: 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.
- Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.
- Add Maven dependencies.
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.8.0</version> </dependency> </dependencies>
- 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 ) { // We recommend that you use the connection string URI to ensure high availability. // 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 AliCoudDB 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(); } } }
- In the IDE tool, click Run.
Python
Related link: MongoDB Python Driver.
Python 3.9 is used in the example.
- Install PyMongo.
pip install pymongo
- Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.
- Save the following sample code as Main.py:
# Python 3.9 is used to run the code. from pymongo import MongoClient # We recommend that you use the connection string URI to ensure high availability. # 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()
- Run the
python3.9 Main.py
command.
C#
Related link: MongoDB C# Driver.
IDE (Visual Studio) is used in the example.
- Use the NuGet package management tool in Visual Studio ( ) to download the following package.
MongoDB.Driver
- Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.
- 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) { // We recommend that you use the connection string URI to ensure high availability. // 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); } } } }
- In the IDE tool, click Run.
Go
Related link: MongoDB Go Driver.
- Run the following command to install the driver package:
go get go.mongodb.org/mongo-driver
- Obtain the information used to connect to the replica set instance. For more information, see Connect to a replica set instance.
- 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() { // We recommend that you use the connection string URI to ensure high availability. // 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) }
- Run the
go run main.go
command.