Loading...
Searching...
No Matches
Connecting to MongoDB

The next step in our journey is to connect to MongoDB: to a single server and to a replicaset alike.

Our first task is to connect to a MongoDB server, listening on localhost's 27017 port. And we don't care whether it is a master or a secondary, so we set the slave_ok argument to TRUE:

void
tut_sync_connect (void)
{
mongo_sync_connection *conn;
conn = mongo_sync_connect ("localhost", 27017, TRUE);
if (!conn)
{
perror ("mongo_sync_connect()");
exit (1);
}
mongo_sync_disconnect (conn);
mongo_sync_disconnect
void mongo_sync_disconnect(mongo_sync_connection *conn)
Close and free a synchronous MongoDB connection.
Definition mongo-sync.c:396
mongo_sync_connect
mongo_sync_connection * mongo_sync_connect(const gchar *address, gint port, gboolean slaveok)
Synchronously connect to a MongoDB server.
Definition mongo-sync.c:201
}

It's fairly straightforward: error handling is done using errno values, because that saves us from inventing our own statuses: POSIX provides us with plenty, and the C library uses errno extensively well. So does libmongo-client!

Next up, is connecting to a replicaset:

void
tut_sync_connect_replica (void)
{
mongo_sync_connection *conn;
conn = mongo_sync_connect ("mongo-master", 27017, TRUE);
if (!conn)
{
perror ("mongo_sync_connect()");
return;
}

Wait a minute! Does this look familiar? Isn't it exactly the same as in the former example (apart from the host name)? It sure is! There really is no difference between connecting to a single server and to a replica set when using the Sync API. It hides all the boring things from the user.

However, if the server is a replicaset, we can add seeds: seeds are hosts that are not listed in the replicaset's public config (meaning they're hidden), but we still want to be able to use them, if so need be.

It's not neccessary to add seeds, if the replica set itself advertises secondaries: the library will discover those, and reconnect to them, if automatic reconnection is turned on. Lets just do that!

if (!mongo_sync_conn_set_auto_reconnect (conn, TRUE))
{
perror ("mongo_sync_conn_set_auto_reconnect()");
return;
}
mongo_sync_conn_set_auto_reconnect
gboolean mongo_sync_conn_set_auto_reconnect(mongo_sync_connection *conn, gboolean auto_reconnect)
Set the state of the auto-reconnect flag on a sync connection.
Definition mongo-sync.c:490

Then we can add the seeds:

if (!mongo_sync_conn_seed_add (conn, "mongo-replica", 27017))
{
perror ("mongo_sync_conn_seed_add()");
return;
}
mongo_sync_conn_seed_add
gboolean mongo_sync_conn_seed_add(mongo_sync_connection *conn, const gchar *host, gint port)
Add a seed to an existing MongoDB connection.
Definition mongo-sync.c:219
if (!mongo_sync_conn_seed_add (conn, "mongo-replica-2", 27017))
{
perror ("mongo_sync_conn_seed_add()");
return;
}

And that's about it! We wrap up our function, and we're done!

mongo_sync_disconnect (conn);
}