Search code examples
mongodbdnsconsul

how to use custom service name in mongodb+srv scheme?


According to the documentation https://www.mongodb.com/docs/v4.4/reference/connection-string/#std-label-connections-dns-seedlist mongodb+srv://server.example.com/ is equivalent to _mongodb._tcp.server.example.com record.

However, I have multiple Mongo services, and I want to connect to _mymongodb._tcp.server.example.com. How do I specify to use mymongodb service name instead of mongodb? I have been staring at the documentation for hours, and I can't seem to find out.


Solution

  • It's not possible, the string _mongodb._tcp is prefixed with the host name, and it is hardcoded in the source code. https://github.com/mongodb/mongo/blob/3e63636e66ced4aed6d1aaaafcdca7ae19cf96f2/src/mongo/client/mongo_uri.cpp#L408

    The only possible way is to handle that manually, for example in Linux shell with:

    srvs=$(dig +short SRV _mymongodb._tcp.server.example.com | awk '{print $4":"$3}' | paste -d,)
    mongo "mongodb://$srvs/"