---
title: "MongoDB 标准连接字符串"
author: "sherryxiu"
date: "2015-04-10T15:22:15Z"
tags: []
categories: ["数据库"]
slug: "mongodb"
draft: false
lastmod: "2015-04-10T15:24:53Z"
id: 2201074
url: "https://sherryxiu.iteye.com/blog/2201074"
---

在一篇文章中看到这样一个连接串“mongodb://python:oracle@192.168.4.167:27017”，python:oracle这个让我百思不得其解，以为和python有关，网上查了好久没有查出来。

原来是username和pwd.![哭](http://www.iteye.com/javascripts/tinymce/plugins/emotions/img/smiley-cry.gif "哭")

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）

`mongodb://localhost`

使用用户fred和密码foobar连接

`mongodb://fred:foobar@localhost`

使用用户fred和密码foobar连接，指定数据库baz

`mongodb://fred:foobar@localhost/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`

使用安全模式连接

`mongodb://localhost/?safe=true`

安全模式下连接到一组Replica Sets，等待至少两台机器同步成功，并设置两秒的超时时间

`mongodb://host1,host2,host3/?safe=true;w=2;wtimeoutMS=2000`

连接池（Connection Pooling）  
服务器每个TCP连接对应一个进程。强力推荐你在应用程序中实现自身的连接池。多数驱动程序也会在背后悄悄帮你做连接池。一个常见的例外是你的应用会为每个请求重新配置一个新进程譬如CGI和PHP。