O ApsaraDB for MongoDB é totalmente compatível com o protocolo MongoDB. Este tópico apresenta exemplos de código para conectar a uma instância de conjunto de réplicas em diferentes linguagens.
Pré-requisitos
Baixe e instale o driver oficial da sua linguagem. Para mais informações, acesse MongoDB Drivers.
Observações de uso
Se a senha da conta da instância de conjunto de réplicas contiver caracteres especiais (! @ # $ % ^ & * ( ) _ + =), aplique escape nesses caracteres na string de conexão. A tabela a seguir lista os caracteres especiais e seus respectivos códigos de escape.
|
Caractere especial |
Caractere de escape |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Por exemplo, se a senha original for ab@#c, converta-a para ab%40%23c na string de conexão.
Usar Node.js para conectar a uma instância de conjunto de réplicas
Para mais informações sobre o Node.js Driver for MongoDB, consulte MongoDB Node.js Driver.
-
Execute o comando a seguir no cliente para inicializar o projeto:
mkdir node-mongodb-demo cd node-mongodb-demo npm init -y -
Instale o pacote do driver com o comando abaixo:
npm install mongodb Obtenha as informações necessárias para conectar à instância de conjunto de réplicas. Para mais detalhes, consulte Conectar a uma instância de conjunto de réplicas.
-
Salve o código de exemplo a seguir como um arquivo 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); Execute o comando
node Node.js.
Usar PHP para conectar a uma instância de conjunto de réplicas
Para mais informações sobre o PHP Driver for MongoDB, consulte MongoDB PHP Driver.
-
Instale o pacote do driver executando o comando a seguir:
$ 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 Obtenha as informações necessárias para conectar à instância de conjunto de réplicas. Para mais detalhes, consulte Conectar a uma instância de conjunto de réplicas.
-
Salve o código de exemplo a seguir como 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"; } ?> Execute o comando
php -f main.php.
Usar Java para conectar a uma instância de conjunto de réplicas
Para mais informações sobre o Java Driver for MongoDB, consulte MongoDB Java Driver.
Os exemplos utilizam IDEs (IntelliJ IDEA e Eclipse IDE). Para conectar a uma instância de conjunto de réplicas em um ambiente de IDE, instale o JDK 8 ou superior.
Obtenha as informações necessárias para conectar à instância de conjunto de réplicas. Para mais detalhes, consulte Conectar a uma instância de conjunto de réplicas.
-
Adicione as dependências do Maven.
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.8.0</version> </dependency> </dependencies> -
Utilize o código de exemplo Java a seguir.
NotaO código abaixo demonstra como configurar manualmente uma conexão com uma instância do ApsaraDB for MongoDB. Se você utilizar essa configuração em um projeto Spring Boot, adicione
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration,class})para desativar a configuração automática e evitar falhas de conexão por conflitos de configuração.// 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(); } } } Na IDE, clique em Run.
Usar Python para conectar a uma instância de conjunto de réplicas
Para mais informações sobre o Python Driver for MongoDB, consulte MongoDB Python Driver.
O exemplo utiliza a versão Python 3.9.
-
Instale o PyMongo.
pip install pymongo Obtenha as informações necessárias para conectar à instância de conjunto de réplicas. Para mais detalhes, consulte Conectar a uma instância de conjunto de réplicas.
-
Salve o código de exemplo a seguir como 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() Execute o comando
python3.9 Main.py.
Usar C# para conectar a uma instância de conjunto de réplicas
Para mais informações sobre o C# Driver for MongoDB, consulte MongoDB C# Driver.
O exemplo utiliza a IDE Visual Studio.
-
Use a ferramenta de gerenciamento de pacotes NuGet no Visual Studio () para baixar o seguinte pacote:
MongoDB.Driver Obtenha as informações necessárias para conectar à instância de conjunto de réplicas. Para mais detalhes, consulte Conectar a uma instância de conjunto de réplicas.
-
Utilize o código de exemplo C# a seguir:
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); } } } } Na IDE, clique em Run.
Usar Go para conectar a uma instância de conjunto de réplicas
Para mais informações sobre o Go Driver for MongoDB, consulte MongoDB Go Driver.
-
Instale o pacote do driver com o comando abaixo:
go get go.mongodb.org/mongo-driver Obtenha as informações necessárias para conectar à instância de conjunto de réplicas. Para mais detalhes, consulte Conectar a uma instância de conjunto de réplicas.
-
Salve o código de exemplo a seguir como 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) } Execute o comando
go run main.go.