Chapter 12. 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

MongoDB client libraries (“drivers” in MongoDB parlance) are designed to manage communication with MongoDB servers, regardless of whether the server is a standalone MongoDB instance or a replica set. For replica sets, by default, drivers 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 class (or equivalent) in your driver and provide a seed list for the driver to connect to. A seed list is simply a list of server addresses. Seeds are members of the replica set your application will read from and write data to. You do not need to list all members in the seed list (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,server-3:27017"

See your driver’s documentation for details.

To provide further resilience, you should also use the DNS Seedlist Connection format to specify how your applications connect ...

Get MongoDB: The Definitive Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.