全部产品
云数据库 MongoDB 版

程序代码连接

更新时间:2017-06-14 10:09:58   分享:   

相关链接

MongoDB Drivers

Connection String URI Format

Node.js 连接示例

相关链接

MongoDB Node.js Driver

项目初始化

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

安装驱动包以及工具包

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

获取云数据库 MongoDB 连接信息

请查看 MongoDB 连接信息七要素获取方法

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. // 官方建议使用的方案
  15. var url = sprintf("mongodb://%s:%d,%s:%d/%s?replicaSet=%s", host1, port1, host2, port2, demoDb, replSetName);
  16. console.info("url:", url);
  17. // 获取mongoClient
  18. mongoClient.connect(url, function(err, db) {
  19. if(err) {
  20. console.error("connect err:", err);
  21. return 1;
  22. }
  23. // 授权. 这里的username基于admin数据库授权
  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. // 取得Collecton句柄
  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. // 插入数据
  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. // 读取数据
  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. //关闭Client,释放资源
  51. db.close();
  52. });
  53. });
  54. });
  55. });

PHP 连接示例

相关链接

Mongodb php driver

安装驱动包以及工具包

  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"

获取云数据库MongoDB的连接信息

请查看 MongoDB 连接信息七要素获取方法

PHP Demo Code

  1. <?php
  2. require 'vendor/autoload.php'; // include Composer goodies
  3. # 实例信息
  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. # 根据实例信息构造mongodb connection string
  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 连接示例

相关链接

官方Quick Start

Jar包下载

获取云数据库 MongoDB 连接信息

请查看 MongoDB 连接信息七要素获取方法

Java Demo Code

Maven配置
  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. // 构建Seed列表
  26. List<ServerAddress> seedList = new ArrayList<ServerAddress>();
  27. seedList.add(seed1);
  28. seedList.add(seed2);
  29. // 构建鉴权信息
  30. List<MongoCredential> credentials = new ArrayList<MongoCredential>();
  31. credentials.add(MongoCredential.createScramSha1Credential(username,
  32. DEFAULT_DB, password.toCharArray()));
  33. // 构建操作选项,requiredReplicaSetName属性外的选项根据自己的实际需求配置,默认参数满足大多数场景
  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. //另一种通过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. // 取得Collecton句柄
  54. MongoDatabase database = client.getDatabase(DEMO_DB);
  55. MongoCollection<Document> collection = database.getCollection(DEMO_COLL);
  56. // 插入数据
  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. // 读取数据
  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. //关闭Client,释放资源
  72. client.close();
  73. }
  74. return ;
  75. }
  76. }

Python 连接示例

相关链接

pymongo下载地址

官方文档

安装pymongo

  1. pip install pymongo

获取云数据库MongoDB连接信息

请查看 MongoDB 连接信息七要素获取方法

Python Demo Code

  1. import uuid
  2. from pymongo import MongoClient
  3. #两地址
  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. #获取mongoclient
  10. client = MongoClient([CONN_ADDR1, CONN_ADDR2], replicaSet=REPLICAT_SET)
  11. #授权. 这里的user基于admin数据库授权
  12. client.admin.authenticate(username, password)
  13. #使用test数据库的collection:testColl做例子, 插入doc, 然后根据DEMO名查找
  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

更多程序代码连接示例请参见MongoDB官网。

本文导读目录
本文导读目录
以上内容是否对您有帮助?