mongodbdockerpymongo

Problem initiating ReplicaSet node using pymongo


I'm trying to write a python script which goal is to initiate a MongoDB replicaset node in my development environment (note: I have just one single node) without having to use mongo shell. So the script is intended to be manually run once.

I run MongoDB using docker and this is part of my docker-compose file:

mongodb:
    image: "mongo:5.0-focal"
    ports:
      - "27017:27017"
    volumes:
      - mongodb:/data/db    
    entrypoint:
      [
        "/usr/bin/mongod",
        "--bind_ip_all",
        "--replSet",
        "rs0" 
      ]

I run the following python code in another docker container belonging to the same network so that it has visibility on the host name mongodb. My pymongo version is 4.0.1

import os
from pymongo import MongoClient

try:
    client = MongoClient('mongodb',27017,serverSelectionTimeoutMS=5000)
    config = { '_id': 'rs0', 'members': [{'_id': 0, 'host': 'mongodb:27017'}]}
    print("REPLICA SET config:")
    print(config)
    out = client.admin.command("replSetInitiate", config)
    print(out)
except Exception as e:
    print("Error!")
    print(e)
    pass

running the script I've got this error:

No servers match selector "Primary()", Timeout: 5.0s, Topology Description: <TopologyDescription id: 61c0dffc7f72958bdd10e65f, topology_type: Unknown, servers: [<ServerDescription ('mongodb', 27017) server_type: RSGhost, rtt: 0.004416499999933876>]>

Ok, no server matches Primary selector, but how can I have a Primary if I don't initiate a replicaSet first? Not an expert in pymongo and MongoDB but am I missing something here?


Solution

  • I was facing similar issue and came across https://jira.mongodb.org/browse/PYTHON-3027. Passing 'directConnection=True' as a parameter to MongoClient seemed to help. Although, am not sure about how this works.

    MongoClient('mongodb://localhost:27017', directConnection=True)