MongoDB - Connection
In this tutorial we will discuss the different ways of connecting to MongoDB.
Starting the MongoDB service
In the previous tutorial, we discussedhow to start the MongoDB service, you only need to execute in the bin directory of the MongoDB installation directory mongodb .
After the startup operation, mongodb will not output anything after printing some necessary information, and then waits for a connection to be established. When a connection is established, it will start printing log information.
You can use the MongoDB shell to connect to the MongoDB server. You can also use PHP to connect to MongoDB. In this tutorial we will use the MongoDB shell to connect to the Mongodb service; in later chapters we will introduce how to connect to MongoDB through PHP, Python, and Node.js.
Standard URI connection syntax:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
mongodb://: Protocol header, indicating the use of MongoDB.[username:password@]: (Optional) authentication information, including username and password.host1[:port1][,...hostN[:portN]]: Server address and port, which can be the address and port of one or more MongoDB servers./[defaultauthdb]: (Optional) default authentication database.[?options]: (Optional) connection options.
The standard connection format includes several options, as shown below:
authSource: Specify the authentication database.replicaSet: Specify the name of the replica set.ssl: Enable SSL connection (true or false).readPreference: Specify the read preference, such asprimary,primaryPreferred,secondary,secondaryPreferred,nearest。connectTimeoutMS: Specify the connection timeout (in milliseconds).socketTimeoutMS: Specify the socket timeout (in milliseconds).
Connect to a local MongoDB instance (default port 27017):
mongodb://localhost
Connect to a local MongoDB instance, specifying a database:
mongodb://localhost/mydatabase
Connect to a local MongoDB instance using a username and password:
mongodb://username:password@localhost/mydatabase
Connect to a remote MongoDB instance:
mongodb://remotehost:27017
Connect to a Replica Set:
mongodb://host1:27017,host2:27017,host3:27017/mydatabase?replicaSet=myReplicaSet
Connect to MongoDB using SSL:
mongodb://username:password@localhost:27017/mydatabase?ssl=true
Connect using multiple options:
mongodb://username:password@localhost:27017/mydatabase?authSource=admin&ssl=true
Python (PyMongo)
Example
from
pymongo
import
MongoClient
client
=
MongoClient
(
'mongodb://user:password@localhost:27017/mydatabase?authSource=admin'
)
db
=
client
[
'mydatabase'
]
Node.js (Mongoose)
Example
const
mongoose
=
require
(
'mongoose'
)
;
mongoose.
connect
(
'mongodb://user:password@localhost:27017/mydatabase?authSource=admin'
,
{
useNewUrlParser
:
true
,
useUnifiedTopology
:
true
}
)
;
const
db
=
mongoose.
connection
;
db.
on
(
'error'
,
console.
error
.
bind
(
console
,
'connection error:'
)
)
;
db.
once
(
'open'
,
function
(
)
{
console.
log
(
'Connected to MongoDB'
)
;
}
)
;
PHP (Mongoose)
Example
selectDatabase ( 'mydatabase' ) ; // select database $collection = $database -> selectCollection ( 'mycollection' ) ; // select collection // insert document $result = $collection -> insertOne ( [ 'name' => 'Alice' , 'age' => 30 ] ) ; echo "Inserted with Object ID '{$result->getInsertedId()}'" ; // query document $document = $collection -> findOne ( [ 'name' => 'Alice' ] ) ; echo "Found document: " . json_encode ( $document ) ; ?>Java
Example
import
com.mongodb.client.MongoClient
;
import
com.mongodb.client.MongoClients
;
import
com.mongodb.client.MongoDatabase
;
public
class
MongoDBConnection
{
public
static
void
main
(
String
[
]
args
)
{
String
uri
=
"mongodb://user:password@localhost:27017/mydatabase?authSource=admin"
;
try
(
MongoClient mongoClient
=
MongoClients.
create
(
uri
)
)
{
MongoDatabase database
=
mongoClient.
getDatabase
(
"mydatabase"
)
;
System
.
out
.
println
(
"Connected to MongoDB"
)
;
}
}
}
Example
Use the default port to connect to the MongoDB service.
mongodb://localhost
Connect to the MongoDB service through the shell:
./mongosh
Current Mongosh Log ID: 66792d6b87657ebec9ed70f1
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.9
Using MongoDB: 7.0.11
Using Mongosh: 2.2.9
At this time, you go back and check the window running the ./mongod command, and you can see where the connection to the MongoDB server is made. You can see the following information:
……省略信息……
2015-09-25T17:22:27.336+0800 I CONTROL [initandlisten] allocator: tcmalloc
2015-09-25T17:22:27.336+0800 I CONTROL [initandlisten] options: { storage: { dbPath: "/data/db" } }
2015-09-25T17:22:27.350+0800 I NETWORK [initandlisten] waiting for connections on port 27017
2015-09-25T17:22:36.012+0800 I NETWORK [initandlisten] connection accepted from 127.0.0.1:37310 #1 (1 connection now open) # 该行表明一个来自本机的连接
……省略信息……
MongoDB connection command format
To connect to a MongoDB server using a username and password, you must use the 'username:password@hostname/dbname' format, where 'username' is the username and 'password' is the password.
Connect and log in to the default database using a username and password:
$ ./mongosh
MongoDB shell version: 4.0.9
connecting to: test
Connect to the local MongoDB service using user admin with password 123456. The output result is as follows:
> mongodb://admin:123456@localhost/
...
Connect and log in to a specified database using a username and password, in the following format:
mongodb://admin:123456@localhost/test
More connection examples
Connect to a local database server, with the default port.
mongodb://localhost
Use username fred and password foobar to log in to the admin database of localhost.
mongodb://fred:foobar@localhost
Use username fred and password foobar to log in to the baz database of localhost.
mongodb://fred:foobar@localhost/baz
Connect to a replica pair, server 1 is example1.com and server 2 is example2.
mongodb://example1.com:27017,example2.com:27017
Connect to a replica set of three servers (ports 27017, 27018, and 27019):
mongodb://localhost,localhost:27018,localhost:27019
Connect to a replica set of three servers, with write operations applied to the primary server and distributed queries to the secondary servers.
mongodb://host1,host2,host3/?slaveOk=true
Directly connect to the first server, whether it is part of a replica set, a primary server, or a secondary server.
mongodb://host1,host2,host3/?connect=direct;slaveOk=true
When your connection server has priorities and you need to list all servers, you can use the above connection method.
Connect to localhost in safe mode:
mongodb://localhost/?safe=true
Connect to a replica set in safe mode, and wait for at least two replication servers to write successfully, with the timeout set to 2 seconds.
mongodb://host1,host2,host3/?safe=true;w=2;wtimeoutMS=2000