Connecting to MongoDB replica set with rmongodb

2020-08-05 10:29发布

问题:

Has anyone been able to connect to a MongoDB replica set using rmongodb? No matter how I configure mongo.create I get an authentication error, even though the same host/username/password work fine when connecting via the mongo shell.

My code does the equivalent of:

> mongo.create(c("rs-1.mysite.com:12345","rs-2.mysite.com:12345"), "rsName", "user", "password", "my_db")
Unable to connect to replset
Authentication failed.

Update:

Looking at the logs of all the nodes in the replica set, I do not see any attempt to authenticate when I run the code above. Therefore, this may be a rmongodb bug.

回答1:

As Sim has noted, rmongodb 1.0.3 does not resolve hostnames.

It is, however, possible to connect to replica sets from rmongodb with with a few caveats:

  • you must include all hostnames (if the primary isn't found in the seed host list, rmongodb will fail to connect)
  • hostnames must be provided as IPs
  • if using an admin user, you must first auth to the admin database (this, at least, is expected behaviour but worth noting)
  • I could only get the connection to work by not providing a replSet name

So my working connect string looks like:

mongo.create(c("192.168.1.123:27017","192.168.1.124:27018","192.168.1.125:27017"),"","user","password", "thedb")

NB: I only tested this with MongoDB 2.2.0.



回答2:

Looking at the C source, it seems that rmongodb does not resolve hostnames into IP addresses. The only way this works is if you pass an IP address string to the driver...

By passing an IP address and port number you can connect to one of the nodes. I still cannot get rmongodb to successfully connect to a replica set.