edit-icon download-icon

MongoDB driver connection

Last Updated: Nov 01, 2017

MongoDB Drivers

Connection String URI Format

Note: The connection examples in this document ONLY apply to the connection string provided on the MongoDB console.

Node.js connection example

MongoDB Node.js Driver

Item initialization

  1. mkdir node-mongodb-demo
  2. cd node-mongodb-demo
  3. npm init

Install driver package and toolkit

  1. npm install mongodb node-uuid sprintf-js save

Obtain ApsaraDB for MongoDB connection information

See Retrieve seven MongoDB connection elements.

Node.js Demo Code

  1. 'use strict';
  2. var uuid = require('node-uuid');
  3. var sprintf = require("sprintf-js").sprintf;
  4. var mongoClient = require('mongodb').MongoClient;
  5. var host1 = "demotest-1.mongodb.tbc3.newtest.rdstest.aliyun-inc.com";
  6. var port1 = 27017;
  7. var host2 = "demotest-2.mongodb.tbc3.newtest.rdstest.aliyun-inc.com";
  8. var port2 = 27017;
  9. var username = "demouser";
  10. var password = "123456";
  11. var replSetName = "mgset-1441984991";
  12. var demoDb = "test";
  13. var demoColl = "testColl";
  14. // Officially recommended solution
  15. var url = sprintf("mongodb://%s:%d,%s:%d/%s?replicaSet=%s", host1, port1, host2, port2, demoDb, replSetName);
  16. console.info("url:", url);
  17. // Retrieve mongoClient.
  18. mongoClient.connect(url, function(err, db) {
  19. if(err) {
  20. console.error("connect err:", err);
  21. return 1;
  22. }
  23. // Authorization. Here, the username is based on the admin database authorization.
  24. var adminDb = db.admin();
  25. adminDb.authenticate(username, password, function(err, result) {
  26. if(err) {
  27. console.error("authenticate err:", err);
  28. return 1;
  29. }
  30. // Get the Collection handle.
  31. var collection = db.collection(demoColl);
  32. var demoName = "NODE:" + uuid.v1();
  33. var doc = {"DEMO": demoName, "MESG": "Hello AliCoudDB For MongoDB"};
  34. console.info("ready insert document: ", doc);
  35. // Insert data.
  36. collection.insertOne(doc, function(err, data) {
  37. if(err) {
  38. console.error("insert err:", err);
  39. return 1;
  40. }
  41. console.info("insert result:", data["result"]);
  42. // Read data.
  43. var filter = {"DEMO": demoName};
  44. collection.find(filter).toArray(function(err, items) {
  45. if(err) {
  46. console.error("find err:", err);
  47. return 1;
  48. }
  49. console.info("find document: ", items);
  50. //Close the client and release resources.
  51. db.close();
  52. });
  53. });
  54. });
  55. });

PHP connection example

Mongodb php driver

Install driver package and toolkit

  1. $ pecl install mongodb
  2. $ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
  3. $ composer require "mongodb/mongodb=^1.0.0"

Obtain ApsaraDB for MongoDB connection information

See Retrieve seven MongoDB connection elements.

PHP Demo Code

  1. <?php
  2. require 'vendor/autoload.php'; // include Composer goodies
  3. # Instance information
  4. $demo_seed1 = 'demotest-1.mongodb.test.aliyun-inc.com:3717';
  5. $demo_seed2 = 'demotest-2.mongodb.test.aliyun-inc.com:3717';
  6. $demo_replname = "mgset-1441984463";
  7. $demo_user = 'root';
  8. $demo_password = '123456';
  9. $demo_db = 'admin';
  10. # Construct the mongodb connection string based on instance information.
  11. # mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
  12. $demo_uri = 'mongodb://' . $demo_user . ':' . $demo_password . '@' .
  13. $demo_seed1 . ',' . $demo_seed2 . '/' . $demo_db . '?replicaSet=' . $demo_replname;
  14. $client = new MongoDB\Client($demo_uri);
  15. $collection = $client->testDb->testColl;
  16. $result = $collection->insertOne( [ 'name' => 'ApsaraDB for Mongodb', 'desc' => 'Hello, Mongodb' ] );
  17. echo "Inserted with Object ID '{$result->getInsertedId()}'", "\n";
  18. $result = $collection->find( [ 'name' => 'ApsaraDB for Mongodb'] );
  19. foreach ($result as $entry)
  20. {
  21. echo $entry->_id, ': ', $entry->name, "\n";
  22. }
  23. ?>

Java connection example

Official Quick start.

JAR package Download.

Obtain ApsaraDB for MongoDB connection information

See Retrieve seven MongoDB connection elements.

Java Demo Code

Maven configuration
  1. <dependencies>
  2. <dependency>
  3. <groupId>org.mongodb</groupId>
  4. <artifactId>mongo-java-driver</artifactId>
  5. <version>3.0.4</version>
  6. </dependency>
  7. </dependencies>
Java Code
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.UUID;
  4. import org.bson.BsonDocument;
  5. import org.bson.BsonString;
  6. import org.bson.Document;
  7. import com.mongodb.MongoClient;
  8. import com.mongodb.MongoClientOptions;
  9. import com.mongodb.MongoClientURI;
  10. import com.mongodb.MongoCredential;
  11. import com.mongodb.ServerAddress;
  12. import com.mongodb.client.MongoCollection;
  13. import com.mongodb.client.MongoCursor;
  14. import com.mongodb.client.MongoDatabase;
  15. public class Main {
  16. public static ServerAddress seed1 = new ServerAddress("demotest-1.mongodb.tbc3.newtest.rdstest.aliyun-inc.com", 27017);
  17. public static ServerAddress seed2 = new ServerAddress("demotest-2.mongodb.tbc3.newtest.rdstest.aliyun-inc.com", 27017);
  18. public static String username = "demouser";
  19. public static String password = "123456";
  20. public static String ReplSetName = "mgset-1441984463";
  21. public static String DEFAULT_DB = "admin";
  22. public static String DEMO_DB = "test";
  23. public static String DEMO_COLL = "testColl";
  24. public static MongoClient createMongoDBClient() {
  25. // Construct the Seed list.
  26. List<ServerAddress> seedList = new ArrayList<ServerAddress>();
  27. seedList.add(seed1);
  28. seedList.add(seed2);
  29. // Construct authentication information.
  30. List<MongoCredential> credentials = new ArrayList<MongoCredential>();
  31. credentials.add(MongoCredential.createScramSha1Credential(username,
  32. DEFAULT_DB, password.toCharArray()));
  33. // For the construction operation options, you can configure options besides the requiredReplicaSetName attribute based on your actual needs, but the default parameters are sufficient in most of the scenarios.
  34. MongoClientOptions options = MongoClientOptions.builder()
  35. .requiredReplicaSetName(ReplSetName).socketTimeout(2000)
  36. .connectionsPerHost(1).build();
  37. return new MongoClient(seedList, credentials, options);
  38. }
  39. public static MongoClient createMongoDBClientWithURI() {
  40. //Initialize the other through URI.
  41. //mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
  42. MongoClientURI connectionString = new MongoClientURI("mongodb://" + username + ":" + password + "@" +
  43. seed1 + "," + seed2 + "/" +
  44. DEFAULT_DB +
  45. "?replicaSet=" + ReplSetName);
  46. return new MongoClient(connectionString);
  47. }
  48. public static void main(String args[]) {
  49. MongoClient client = createMongoDBClient();
  50. //or
  51. //MongoClient client = createMongoDBClientWithURI();
  52. try {
  53. // Get the Collection handle.
  54. MongoDatabase database = client.getDatabase(DEMO_DB);
  55. MongoCollection<Document> collection = database.getCollection(DEMO_COLL);
  56. // Insert data.
  57. Document doc = new Document();
  58. String demoname = "JAVA:" + UUID.randomUUID();
  59. doc.append("DEMO", demoname);
  60. doc.append("MESG", "Hello AliCoudDB For MongoDB");
  61. collection.insertOne(doc);
  62. System.out.println("insert document: " + doc);
  63. // Read data.
  64. BsonDocument filter = new BsonDocument();
  65. filter.append("DEMO", new BsonString(demoname));
  66. MongoCursor<Document> cursor = collection.find(filter).iterator();
  67. while (cursor.hasNext()) {
  68. System.out.println("find document: " + cursor.next());
  69. }
  70. } finally {
  71. //Close the client and release resources.
  72. client.close();
  73. }
  74. return ;
  75. }
  76. }

Python connection example

pymongo download address

Official documentation

Install PyMongo

  1. pip install pymongo

Obtain ApsaraDB for MongoDB connection information

See Retrieve seven MongoDB connection elements.

Python Demo Code

  1. import uuid
  2. from pymongo import MongoClient
  3. #Two URLs
  4. CONN_ADDR1 = 'demotest-1.mongodb.tbc3.newtest.rdstest.aliyun-inc.com:27017'
  5. CONN_ADDR2 = 'demotest-2.mongodb.tbc3.newtest.rdstest.aliyun-inc.com:27017'
  6. REPLICAT_SET = 'mgset-1441984463'
  7. username = 'demouser'
  8. password = '123456'
  9. #Retrieve mongoclient
  10. client = MongoClient([CONN_ADDR1, CONN_ADDR2], replicaSet=REPLICAT_SET)
  11. #Authorization. Here, the user is based on the admin database authorization.
  12. client.admin.authenticate(username, password)
  13. #Use "collection:testColl" from the test database as an example, insert doc, and then search by DEMO name.
  14. demo_name = 'python-' + str(uuid.uuid1())
  15. print 'demo_name:', demo_name
  16. doc = dict(DEMO=demo_name, MESG="Hello ApsaraDB For MongoDB")
  17. doc_id = client.test.testColl.insert(doc)
  18. print 'doc_id:', doc_id
  19. for d in client.test.testColl.find(dict(DEMO=demo_name)):
  20. print 'find documents:', d
Thank you! We've received your feedback.