通过程序代码连接MongoDB实例
更新时间:2021-03-11
云数据库MongoDB版完全兼容MongoDB协议,本文介绍各类程序连接数据库的相关示例。
准备工作
- 根据您的实例类型获取云数据库MongoDB连接地址。
- 根据您使用的语言下载并安装官方驱动程序。更多信息,请参见MongoDB Drivers。
说明:
- 本文连接Demo仅适用于百度云提供的MongoDB内网连接地址。
- 连接分片集群实例时,无需指定下列Demo中的replicaSet相关参数。
Node.js 连接示例
相关链接:MongoDB Node.js Driver。
1.项目初始化
mkdir node-mongodb-demo
cd node-mongodb-demo
npm init
2.安装驱动包以及工具包。
npm install mongodb node-uuid sprintf-js
3.根据您的实例类型获取云数据库MongoDB连接信息。
4.Node.js Demo Code。
var host1 = "*********.mongodb.gz.baidubce.com";
var port1 = 27017;
var host2 = "*********.mongodb.gz.baidubce.com";
var port2 = 27017;
var username = "root";
var password = "******";
var replSetName = "rep-******";
var adminDb = 'admin'
var demoDb = "test";
var demoColl = "testColl";
// 官方建议使用的方案
var url = sprintf("mongodb://%s:%s@%s:%d,%s:%d/%s?replicaSet=%s", username, password, host1, port1, host2, port2, adminDb, replSetName);
console.info("url:", url);
//获取mongoClient
mongoClient.connect(url, {useUnifiedTopology: true, useNewUrlParser: true}, function (err, db) {
if (err) {
console.error("connect err:", err);
return 1;
}
//取得Collecton句柄
var collection = db.db(demoDb).collection(demoColl);
var demoName = "NODE:" + uuid.v1();
var doc = { "DEMO": demoName, "MESG": "Hello BaiduCoudDB For MongoDB"};
console.info("ready insert document: ", doc);
// 插入数据
collection.insertOne(doc, function (err, data) {
if (err) {
console.error("insert err:", err);
return 1;
}
console.info("insert result:", data["result"]);
// 读取数据
var filter = { "DEMO": demoName };
collection.find(filter).toArray(function (err, items) {
if (err) {
console.error("find err:", err);
return 1;
}
console.info("find document: ", items);
//关闭Client,释放资源
db.close();
});
});
});
PHP 连接示例
相关链接:MongoDB PHP Driver。
1.安装驱动包以及工具包。
$ pecl install mongodb
$ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
$ composer require "mongodb/mongodb=^1.0.0"
2.获取云数据库 MongoDB 连接信息。
3.PHP Demo Code。
<?php
require 'vendor/autoload.php'; // include Composer goodies
# 实例信息
$demo_seed1 = '*********.mongodb.gz.baidubce.com:27017';
$demo_seed2 = '*********.mongodb.gz.baidubce.com:27017';
$demo_replname = "rep-******";
$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 . '?replicaSet=' . $demo_replname;
echo "demo_uri = '$demo_uri'", "\n";
$client = new MongoDB\Client($demo_uri);
$collection = $client->testDb->testColl;
$result = $collection->insertOne(['name' => 'DocDB for Mongodb', 'desc' => 'Hello, Mongodb']);
echo "Inserted with Object ID '{$result->getInsertedId()}'", "\n";
$result = $collection->find(['name' => 'DocDB for Mongodb']);
foreach ($result as $entry) {
echo $entry->_id, ': ', $entry->name, "\n";
}
?>
Java 连接示例
相关链接:下载Jar包。
1.获取云数据库 MongoDB 连接信息。
2.Java Demo Code。
- Maven配置。
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.6.4</version>
</dependency>
</dependencies>
- Java Code。
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.Document;
public class App {
public static ServerAddress seed1 = new ServerAddress("*********.mongodb.gz.baidubce.com",
27017);
public static ServerAddress seed2 = new ServerAddress("*********.mongodb.gz.baidubce.com",
27017);
public static String username = "root";
public static String password = "*********";
public static String ReplSetName = "rep-******";
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().requiredReplicaSetName(ReplSetName)
.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 + "?replicaSet=" + ReplSetName);
return new MongoClient(connectionString);
}
public static void main(String args[]) {
MongoClient client = createMongoDBClient();
// or
// MongoClient client = createMongoDBClientWithURI();
try {
// 取得Collecton句柄
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 DocDB 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下载地址。
1.安装pymongo。
pip install pymongo
2.获取云数据库 MongoDB 连接信息。
3.Python Demo Code。
import uuid
from pymongo import MongoClient
CONN_ADDR1 = '*********.mongodb.gz.baidubce.com:27017'
CONN_ADDR2 = '*********.mongodb.gz.baidubce.com:27017'
REPLICAT_SET = 'rep-******'
username = 'root'
password = '*********'
client = MongoClient([CONN_ADDR1, CONN_ADDR2], replicaSet=REPLICAT_SET)
client.admin.authenticate(username, password)
demo_name = 'python-' + str(uuid.uuid1())
print 'demo_name:', demo_name
doc = dict(DEMO=demo_name, MESG="Hello DocDB For MongoDB")
doc_id = client.test.testColl.insert(doc)
print 'doc_id:', doc_id
for d in client.test.testColl.find(dict(DEMO=demo_name)):
print 'find documents:', d
C# 连接示例
相关链接:MongoDB C# Driver。
1.安装如下驱动包。
mongocsharpdriver.dll
2.获取云数据库 MongoDB 连接信息。
3.C# Demo Code。
using MongoDB.Driver;
using System;
using System.Collections.Generic;
namespace Baiduyun
{
class Program
{
static void Main(string[] args)
{
//Mongo 实例信息
const string host1 = "*********.mongodb.gz.baidubce.com";
const int port1 = 27017;
const string host2 = "*********.mongodb.gz.baidubce.com";
const int port2 = 27017;
const string replicaSetName = "rep-******";
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 连接示例
相关链接:MongoDB Go Driver。
1.安装如下驱动包。
go get gopkg.in/mgo.v2
下载失败的话建议设置代理:
git config --global --unset http.proxy
git config --global --unset https.proxy
2.获取云数据库 MongoDB 连接信息。
3.Go Demo Code。
package main
import (
"fmt"
"log"
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Person struct {
Name string
Phone string
}
func main() {
fmt.Println("hello world")
dialInfo := &mgo.DialInfo{
Addrs: []string{"*********.mongodb.gz.baidubce.com:27017", "*********.mongodb.gz.baidubce.com:27017"},
Direct: false,
Timeout: time.Second * 1,
Database: "admin",
Source: "admin",
Username: "root",
Password: "*********",
}
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
fmt.Printf("dial failed: %v",err)
return
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("test").C("test_collection")
err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
&Person{"Cla", "+55 53 8402 8510"})
if err != nil {
log.Fatal(err)
}
result := Person{}
err = c.Find(bson.M{"name": "Ale"}).One(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println("Phone:", result.Phone)
}