Unable to connect to secondary from local laptop with pymongo

Hello. Right now I’m experiencing a weird issue where I can’t connect to a secondary from my local laptop but can from a remote server that holds the mongo replica set.

def create_mongo_client(username: str, password : str, server_name : str) -> pymongo.MongoClient:
        connection_string = f"mongodb://{username}:{password}@{server_name}/?readPreference=secondary" 
        mongo_client = pymongo.MongoClient(connection_string)
        print(f"is_primary?: {mongo_client.is_primary}")

This is the code I’m using. Right now, no matter what server I specify, it’ll always connect to the primary. But if I run the same thing on the remote server that holds the mongo replica set, then it’ll let me connect to the secondary. I don’t think this is a firewall issue since it doesn’t give any error or indication that the connection failed to the secondary. It just automatically connects to the primary instead.

mongo_client.is_primary always returns true when connected to a replica set (with an available primary) even if there are also available secondaries:

>>> client = MongoClient(readPreference="secondary")
>>> client.is_primary
>>> client.secondaries
{('localhost', 27017), ('localhost', 27018)}
>>> client.topology_description
<TopologyDescription id: 660aefbf7fec528dc17ee0cd, topology_type: ReplicaSetWithPrimary, servers: [<ServerDescription ('localhost', 27017) server_type: RSSecondary, rtt: 0.0018319159862585366>, <ServerDescription ('localhost', 27018) server_type: RSSecondary, rtt: 0.0024038749979808927>, <ServerDescription ('localhost', 27019) server_type: RSPrimary, rtt: 0.001912207982968539>]>
>>> client.read_preference
Secondary(tag_sets=None, max_staleness=-1, hedge=None)

In this configuration, write operations will be sent to the primary and read operations will be sent to the secondaries.

Note that MongoClient will connect to the entire replica set by default (so that it will be more highly available) even if you only provide a single server.

Is there a way to force it to connect only to the secondary I specify within the connection string for read/write operations? I’m trying to do a compaction/write operations against a specific secondary in the replica set.

Use the directConnection=True option to MongoClient: mongo_client – Tools for connecting to MongoDB - PyMongo 4.7.0.dev0 documentation