云数据库MongoDB版完全兼容MongoDB协议,本文为您介绍使用不同语言的程序代码来连接云数据库分片集群实例。
前提条件
已获取云数据库MongoDB分片集群实例连接地址,如何获取,请参见分片集群实例连接说明。
根据您使用的语言下载并安装官方驱动程序,更多信息,请参见MongoDB Drivers 。
说明
连接云数据库MongoDB分片集群实例时,无需指定Demo中的replicaSet相关参数。
Node.js连接示例
Node.js驱动相关信息,请参见MongoDB Node.js Driver。
在客户端执行如下命令,进行项目初始化。
mkdir node-mongodb-demo cd node-mongodb-demo npm init
执行如下命令,安装驱动包以及工具包。
npm install mongodb node-uuid sprintf-js
获取云数据库MongoDB分片集群实例连接信息。
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; const username = "root"; const password = "*********"; // const replSetName = "mgset-*********"; const demoDb = "test"; const demoColl = "testColl"; // 官方建议使用分片集群实例地址,确保高可用。 const url = sprintf("mongodb://%s:%s@%s:%d,%s:%d/admin", username, password, host1, port1, host2, port2); console.info("url:", url); const client = new MongoClient(url); // 获取mongoClient。 async function run() { try { // 连接实例。 await client.connect(); // 取得数据库句柄。 const database = client.db(demoDb); // 取得Collection句柄。 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); // 插入数据。 const result = await collection.insertOne(doc); console.log( `A document was inserted with the _id: ${result.insertedId}`, ); // 读取数据。 const filter = { "DEMO": demoName }; const findResult = await collection.find(filter); await findResult.forEach(console.dir); } finally { // 关闭连接。 await client.close(); } } run().catch(console.dir);
PHP连接示例
PHP相关信息,请参见MongoDB PHP Driver。
安装驱动包以及工具包。
$ pecl install mongodb $ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"` $ composer require "mongodb/mongodb=^1.0.0"
获取云数据库MongoDB分片集群实例连接信息。
PHP Demo Code。
<?php require 'vendor/autoload.php'; // include Composer goodies # 实例信息。 $demo_seed1 = '**********.mongodb.test.aliyun-inc.com:3717'; $demo_seed2 = '**********.mongodb.test.aliyun-inc.com:3717'; $demo_replname = "mgset-**********"; $demo_user = 'root'; $demo_password = '**********'; $demo_db = 'admin'; # 根据实例信息构造mongodb connection string。 # mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] $demo_uri = 'mongodb://' . $demo_user . ':' . $demo_password . '@' . $demo_seed1 . ',' . $demo_seed2 . '/' . $demo_db; $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连接示例
相关链接:
官方Quick Start文档。
下载Jar包。
获取云数据库MongoDB分片集群实例连接信息。
Java Demo Code。
Maven配置。
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.10</version> </dependency> </dependencies>
Java Code。
package mongodb; 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 shardingConnectTest { public static ServerAddress seed1 = new ServerAddress("11.238.XX.XX", 3717); public static ServerAddress seed2 = new ServerAddress("11.238.XX.XX", 3717); public static String username = "autotest"; public static String password = "autotest"; // 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() { // 构建Seed列表 List<ServerAddress> seedList = new ArrayList<ServerAddress>(); seedList.add(seed1); seedList.add(seed2); // 构建鉴权信息 List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(MongoCredential.createScramSha1Credential(username, DEFAULT_DB, password.toCharArray())); // 构建操作选项,requiredReplicaSetName属性外的选项根据自己的实际需求配置,默认参数满足大多数场景 MongoClientOptions options = MongoClientOptions.builder().socketTimeout(2000).connectionsPerHost(1).build(); return new MongoClient(seedList, credentials, options); } public static MongoClient createMongoDBClientWithURI() { // 另一种通过URI初始化 // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] MongoClientURI connectionString = new MongoClientURI("mongodb://" + username + ":" + password + "@" + seed1 + "," + seed2 + "/" + DEFAULT_DB); return new MongoClient(connectionString); } public static void main(String args[]) { MongoClient client = createMongoDBClientWithURI(); try { // 取得Collection句柄 MongoDatabase database = client.getDatabase(DEMO_DB); MongoCollection<Document> collection = database.getCollection(DEMO_COLL); // 插入数据 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); // 读取数据 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 { // 关闭Client,释放资源 client.close(); } return; } }
Python连接示例
相关文档: pymongo 4.1.1。
安装pymongo。
pip3 install pymongo
获取云数据库MongoDB分片集群实例连接信息。
Python Demo Code。
import sys from pymongo import MongoClient uri = 'mongodb://%s:%s@dds-bp18365e467ea5c4****.mongodb.rds.aliyuncs.com:3717/admin' username = 'root' password = 'MongoDB****' client = MongoClient(uri % (username, password)) ret = client.admin.command('ping')['ok'] if ret: print('ping successfully!') else: print('ping failed!') sys.exit(1) db = client['baz'] coll = db['quz'] uuid = coll.insert_one({'hello': 'world'}).inserted_id print('Id: %s' % uuid) ret = coll.find_one({"_id": uuid}) print(ret)
C#连接示例
C#驱动相关信息,请参见MongoDB C# Driver。
在客户端执行如下命令,安装如下驱动包。
Install-Package mongocsharpdriver
获取云数据库MongoDB分片集群实例连接信息。
C# Demo Code。
using MongoDB.Driver; using System; using System.Collections.Generic; namespace Aliyun { class Program { static void Main(string[] args) { //Mongo 实例信息。 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"; const string userName = "root"; const string passwd = "********"; try { Console.WriteLine("开始连接......."); 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; //设置实例名称。 settings.ReplicaSetName = replicaSetName; //设置超时时间为3秒。 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 = "女"; //插入数据user。 collection.Insert(user); //获取一条数据。 User result = collection.FindOne(); Console.WriteLine("id:" + result.id + " name:" + result.name + " sex:"+result.sex); Console.WriteLine("连接成功........."); } catch (Exception e) { Console.WriteLine("连接异常:"+e.Message); } } } class User { public string id { set; get; } public string name { set; get; } public string sex { set; get; } } }
Go连接示例
Go驱动相关信息,请参见MongoDB Go Driver。
安装如下驱动包。
go get go.mongodb.org/mongo-driver
获取云数据库MongoDB分片集群实例连接信息。
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. clientOpts := options.Client().ApplyURI("mongodb://root:****@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 inheritied 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) } }