Can't run compact command on secondary nodes (will not run compact on an active replica set primary)

I’m trying to run a compact command using pymongo but it returns me will not run compact on an active replica set primary even though the node I’m trying to run is a SECONDARY node. When I connect to to node, using a db client app (MongoDB Compass), I’m able to run the command without force (db.runCommand ( { compact: 'collection_name'} )) just fine. This error only returns on primary node. But how come am I getting this error on a secondary node in my pymongo?

>>> db.command({"compact": collection})
...
...
pymongo.errors.OperationFailure: will not run compact on an active replica set primary as this is a slow blocking operation. use force:true to force, full error: {'ok': 0.0, 'errmsg': 'will not run compact on an active replica set primary as this is a slow blocking operation. use force:true to force', 'operationTime': Timestamp(1676176471, 1), '$clusterTime': {'clusterTime': Timestamp(1676176471, 1), 'signature': {'hash': b'\x7f\xe9\x18w\x86\xb41\r[\x8a\x8fT;\xe3\x8c\xf5\x92\xac\x04\xd1', 'keyId': 7194618855627423746}}}

Please help me understand the root cause. This is frustrating!

Hi @Ercin_Demir

pymongo 4.0+ default to autodiscovery and connection to the replicaset. For these operations you want to connect directly to the Secondary. Add the directConnection=True as a connection parameter and see if it starts to work for you.

5 Likes

This worked! Thanks very much @chris

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.