MongoDB 標准連接字符串
mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]
注:並非所有MongoDB驅動都支持完整的連接字符串,不支持此格式連接字串的驅動會有替代連接方案,具體請參照驅動自身的說明文檔。
mongodb:// 是連接字串必須的前綴字串
username:password@ 可選項,連接到數據庫后會嘗試驗證登陸
host1 必須的指定至少一個host
:portX 可選項,默認連接到27017
/database 如果指定username:password@,連接並驗證登陸指定數據庫。若不指定,默認打開admin數據庫。
?options 是連接選項。如果不使用/database,則前面需要加上/。所有連接選項都是鍵值對name=value,鍵值對之間通過&或;(分號)隔開
連接選項包括:
Replica set:
replicaSet=name
驅動會校驗replica set的名字。意味着給定的hosts是主庫(seed list),驅動將試圖找到replica set中的所有成員。(•The driver verifies that the name of the replica set it connects to matches this name. Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set.)
Single server:
slaveOk=true|false
自由選項:
safe=true|false
true: 驅動程序會在提交每次更新操作后執行getLastError命令以確認更新是有效的(參見w和wtimeoutMS)
false:驅動程序在每次更新操作后不會執行getLastError
w=n
驅動在getLastError命令加上{ w : n } 參數。意味着safe=true
wtimeoutMS=ms
驅動在getLastError命令加上{ wtimeout : ms }參數。意味着safe=true.
fsync=true|false
true: 驅動在getLastError命令加上{ fsync : true } 參數。意味着safe=true.
false: 驅動不在getlasterror 命令加fsync參數。
journal=true|false
true: 同步到 journal. 意味着safe=true.
connectTimeoutMS=ms
設置建立連接超時,單位ms
socketTimeoutMS=ms
設置socket發送或接受超時時間,單位ms
這些選項都是大小寫不敏感的。
連接MongoDB(默認連接到localhost:27017)
使用用戶fred和密碼foobar連接
使用用戶fred和密碼foobar連接,指定數據庫baz
連接到兩台服務器組成的Replica Sets
mongodb://example.com:27017,example2.com:27017
|
連接到三台本地服務器組成的Replica Sets(分別使用27017、27018和27019端口)
mongodb://localhost,localhost:27018,localhost:27019
|
連接到三台服務器組成的Replica Sets,把所有寫操作集中在主庫,讀操作分布在各叢庫
mongodb://host1,host2,host3/?slaveOk=true
|
使用安全模式連接
安全模式下連接到一組Replica Sets,等待至少兩台機器同步成功,並設置兩秒的超時時間
mongodb://host1,host2,host3/?safe=true;w=2;wtimeoutMS=2000
|
連接池(Connection Pooling)
服務器每個TCP連接對應一個進程。強力推薦你在應用程序中實現自身的連接池。多數驅動程序也會在背后悄悄幫你做連接池。一個常見的例外是你的應用會為每個請求重新配置一個新進程譬如CGI和PHP。