Advanced Connections
The following sections contain information specific to certain types of MongoDB configurations. You may not need to use all of them, but understanding their uses is a good idea.
Connecting over SSL
To connect to a MongoDB server enabled with SSL, simply provide the ?ssl=true option in the MongoDB URI.
"mongodb://localhost:27017/?ssl=true"
If the MongoDB C Driver has not been compiled with --enable-ssl, then connecting to a server that does not support SSL will fail if the ?ssl=true parameter is provided in the URI. This is to prevent unintentional information leak.
Connecting to a Replica Set
Connecting to a Replica Set is much like connecting to a single MongoDB server. All that is needed is to alter the connection string URI. The following listing will connect to a Replica Set named myreplset. The hostname myreplset01 should be a member of the configured Replica Set. Notice the addition of replicaSet=myreplset.
#include <bson.h>
#include <mongoc.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_init ();
/* Create our MongoDB Client */
client = mongoc_client_new ("mongodb://myreplset01:27017/?replicaSet=myreplset");
/* do something with client ... */
/* Free our client */
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}You can specify multiple hostnames using the MongoDB connection string URI. The Mongo C Driver will use this information to try to recover in the case of a network partition.
To seed a list of nodes in your Replica Set, use a comma to separate the hostnames.
"mongodb://myreplset01:27017,myreplset02:27017/?replicaSet=myreplset"
Connecting to a UNIX Domain Socket
On UNIX-like systems, you can connect directly to a MongoDB server using a UNIX domain socket. Use the following URI format to specify the path to the socket. The socket path MUST be suffixed with .sock.
"mongodb:///tmp/mongodb-27017.sock"
Connecting directly to a UNIX domain socket is not a common practice.