通過(guò)程序代碼連接MongoDB單節(jié)點(diǎn)實(shí)例
云數(shù)據(jù)庫(kù)MongoDB版完全兼容MongoDB協(xié)議,本文為您介紹使用不同語(yǔ)言的程序代碼來(lái)連接MongoDB單節(jié)點(diǎn)實(shí)例。
前提條件
獲取云數(shù)據(jù)庫(kù)MongoDB副本集實(shí)例連接地址。具體操作,請(qǐng)參見(jiàn)副本集實(shí)例連接說(shuō)明。
根據(jù)您使用的語(yǔ)言下載并安裝官方驅(qū)動(dòng)程序。更多信息,請(qǐng)參見(jiàn)MongoDB Drivers 。
Node.js連接示例
Node.js驅(qū)動(dòng)相關(guān)信息,請(qǐng)參見(jiàn)MongoDB Node.js Driver。
在客戶端執(zhí)行如下命令,進(jìn)行項(xiàng)目初始化。
mkdir node-mongodb-demo cd node-mongodb-demo npm init
執(zhí)行如下命令,安裝驅(qū)動(dòng)包以及工具包。
npm install mongodb node-uuid sprintf-js
獲取云數(shù)據(jù)庫(kù)MongoDB單節(jié)點(diǎn)實(shí)例連接信息。
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; //數(shù)據(jù)庫(kù)賬號(hào)為node-test const username = "node-test"; const password = "*********"; const replSetName = "mgset-*********"; const demoDb = "test"; const demoColl = "testColl"; // 官方建議使用副本集地址,確保高可用。 const url = sprintf("mongodb://%s:%s@%s:%d,%s:%d/admin?replicaSet=%s", username, password, host1, port1, host2, port2, replSetName); console.info("url:", url); const client = new MongoClient(url); // 獲取mongoClient。 async function run() { try { // 連接實(shí)例。 await client.connect(); // 取得數(shù)據(jù)庫(kù)句柄。 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); // 插入數(shù)據(jù)。 const result = await collection.insertOne(doc); console.log( `A document was inserted with the _id: ${result.insertedId}`, ); // 讀取數(shù)據(jù)。 const filter = { "DEMO": demoName }; const findResult = await collection.find(filter); await findResult.forEach(console.dir); } finally { // 關(guān)閉連接。 await client.close(); } } run().catch(console.dir);
PHP連接示例
PHP相關(guān)信息,請(qǐng)參見(jiàn)MongoDB PHP Driver。
安裝驅(qū)動(dòng)包以及工具包。
$ pecl install mongodb $ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"` $ composer require "mongodb/mongodb=^1.0.0"
獲取云數(shù)據(jù)庫(kù)MongoDB單節(jié)點(diǎn)實(shí)例連接信息。
PHP Demo Code。
<?php require 'vendor/autoload.php'; // include Composer goodies # 實(shí)例信息。 $demo_seed1 = '**********.mongodb.test.aliyun-inc.com:3717'; $demo_seed2 = '**********.mongodb.test.aliyun-inc.com:3717'; $demo_replname = "mgset-**********"; # 數(shù)據(jù)庫(kù)賬號(hào)為php-test $demo_user = 'php-test'; $demo_password = '**********'; $demo_db = 'admin'; # 根據(jù)實(shí)例信息構(gòu)造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 . '?replicaSet=' . $demo_replname; $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連接示例
相關(guān)鏈接:
官方Quick Start文檔。
下載Jar包。
獲取云數(shù)據(jù)庫(kù)MongoDB單節(jié)點(diǎn)實(shí)例連接信息。
Java Demo Code。
Maven配置。
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.10</version> </dependency> </dependencies>
Java Code。
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 Main { public static ServerAddress seed1 = new ServerAddress("**********.mongodb.tbc3.newtest.rdstest.aliyun-inc.com", 27017); public static ServerAddress seed2 = new ServerAddress("**********.mongodb.tbc3.newtest.rdstest.aliyun-inc.com", 27017); public static String username = "demouser"; public static String password = "**********"; 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() { // 構(gòu)建Seed列表。 List<ServerAddress> seedList = new ArrayList<ServerAddress>(); seedList.add(seed1); seedList.add(seed2); // 構(gòu)建鑒權(quán)信息。 List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(MongoCredential.createScramSha1Credential(username, DEFAULT_DB, password.toCharArray())); // 構(gòu)建操作選項(xiàng),requiredReplicaSetName屬性外的選項(xiàng)根據(jù)自己的實(shí)際需求配置,默認(rèn)參數(shù)滿足大多數(shù)場(chǎng)景。 MongoClientOptions options = MongoClientOptions.builder().requiredReplicaSetName(ReplSetName) .socketTimeout(2000).connectionsPerHost(1).build(); return new MongoClient(seedList, credentials, options); } public static MongoClient createMongoDBClientWithURI() { // 另一種通過(guò)URI初始化。 // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] MongoClientURI connectionString = new MongoClientURI("mongodb://" + username + ":" + password + "@" + seed1 + "," + seed2 + "/" + DEFAULT_DB + "?replicaSet=" + ReplSetName); return new MongoClient(connectionString); } public static void main(String args[]) { MongoClient client = createMongoDBClient(); // or // MongoClient client = createMongoDBClientWithURI(); try { // 取得Collection句柄。 MongoDatabase database = client.getDatabase(DEMO_DB); MongoCollection<Document> collection = database.getCollection(DEMO_COLL); // 插入數(shù)據(jù)。 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); // 讀取數(shù)據(jù)。 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 { // 關(guān)閉Client,釋放資源。 client.close(); } return; } }
Python連接示例
相關(guān)文檔: pymongo。
安裝pymongo。
pip3 install pymongo
獲取云數(shù)據(jù)庫(kù)MongoDB單節(jié)點(diǎn)實(shí)例連接信息。
Python Demo Code。
import sys from pymongo import MongoClient uri = 'mongodb://%s:%s@dds-bp18365e467ea5c4****.mongodb.rds.aliyuncs.com:3717/admin' # 數(shù)據(jù)庫(kù)賬號(hào)為python-test,鑒權(quán)數(shù)據(jù)庫(kù)為admin username = 'python-test' 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#驅(qū)動(dòng)相關(guān)信息,請(qǐng)參見(jiàn)MongoDB C# Driver。
在客戶端執(zhí)行如下命令,安裝如下驅(qū)動(dòng)包。
Install-Package mongocsharpdriver
獲取云數(shù)據(jù)庫(kù)MongoDB單節(jié)點(diǎn)實(shí)例連接信息。
C# Demo Code。
using MongoDB.Driver; using System; using System.Collections.Generic; namespace Aliyun { class Program { static void Main(string[] args) { //Mongo 實(shí)例信息。 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"; //數(shù)據(jù)庫(kù)賬號(hào)為c-test。 const string userName = "c-test"; const string passwd = "********"; try { Console.WriteLine("開(kāi)始連接......."); 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; //設(shè)置副本集名稱。 settings.ReplicaSetName = replicaSetName; //設(shè)置超時(shí)時(shí)間為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 = "女"; //插入數(shù)據(jù)user。 collection.Insert(user); //獲取一條數(shù)據(jù)。 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驅(qū)動(dòng)相關(guān)信息,請(qǐng)參見(jiàn)MongoDB Go Driver。
安裝如下驅(qū)動(dòng)包。
go get go.mongodb.org/mongo-driver
獲取云數(shù)據(jù)庫(kù)MongoDB單節(jié)點(diǎn)實(shí)例連接信息。
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" "log" ) func main() { // Create a Client to a MongoDB server and use Ping to verify that the // server is running. //數(shù)據(jù)庫(kù)賬號(hào)為go-test,鑒權(quán)數(shù)據(jù)庫(kù)為admin clientOpts := options.Client().ApplyURI("mongodb://go-test:****@dds-bp1*******.mongodb.rds.aliyuncs.com:3717/admin") 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 inherited 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.InsertOne(context.Background(), bson.M{"hello": "world"}) if err != nil { fmt.Println("insert result failed!") log.Fatal(err) return nil, err } id := res.InsertedID fmt.Println("Id: ", id) fmt.Printf("insert result: %v\n", res) 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 nil, err } return result, err }, txnOpts) if err == nil { fmt.Printf("result: %v\n", result) } }
常見(jiàn)問(wèn)題
通過(guò)程序代碼連接實(shí)例時(shí)報(bào)錯(cuò),您可以從以下兩個(gè)方面排查:
網(wǎng)絡(luò)互通。您可以通過(guò)MongoShell連接實(shí)例,測(cè)試網(wǎng)絡(luò)連通性。具體操作,請(qǐng)參見(jiàn)通過(guò)Mongo Shell連接MongoDB單節(jié)點(diǎn)實(shí)例。
代碼問(wèn)題。在確認(rèn)網(wǎng)絡(luò)通暢后,請(qǐng)檢查代碼以及運(yùn)行環(huán)境配置是否存在問(wèn)題。