O'Reilly logo

MongoDB: The Definitive Guide, 2nd Edition by Kristina Chodorow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 11. Connecting to a Replica Set from Your Application

This chapter covers how applications interact with replica sets, including:

  • How connections and failovers work

  • Waiting for replication on writes

  • Routing reads to the correct member

Client-to-Replica-Set Connection Behavior

From an application’s point of view, a replica set behaves much like a standalone server. By default, client libraries will connect to the primary and route all traffic to it. Your application can perform reads and writes as though it were talking to a standalone server while your replica set quietly keeps hot standbys ready in the background.

Connections to a replica set are similar to connections to a single server. Use the MongoClient-equivalent in your driver and provide a list of seeds for the driver to connect to. Seeds are members of the replica set. You do not have to list all members (although you can): when the driver connects to the seeds, it will discover the other members from them. A connection string usually looks something like this:

"mongodb://server-1:27017,server-2:27017"

See your driver’s documentation for details.

When a primary goes down, the driver will automatically find the new primary (once one is elected) and will route requests to it as soon as possible. However, while there is no reachable primary your application will be unable to perform writes.

There may be no primary available for a brief time (during an election) or for an extended period of time (if no reachable member can become ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required