Connection to db via script

I am interested in working in a text editor instead of directly in mongo shell, so I would like to set up a script which connects to the class atlas cluster. I have looked at the documentation and tried to use the connection string given but I cannot get the connection to work. Can somebody give some advice on how to do this?

What exact connection string did you use? How did you use it? What was the error message? These are some of the basic things that should be included in a thread.

I’d recommend using MongoDB Compass as well.

Welcome to the discussion board.

Hi, thanks for getting back to me.

For reference, the connection string given in class, which works in the shell is:

mongo "mongodb://cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017/aggregations?replicaSet=Cluster0-shard-0" --authenticationDatabase admin --ssl -u m121 -p aggregations --norc

I tried to implement this connection string in javascript, but I wasn’t sure how to include the flags

  • –authenticationDatabase admin
  • –ssl
  • –norc

Anyway, I wrote a script like this:

conn = new Mongo();
let conString = "mongodb://cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017/aggregations?replicaSet=Cluster0-shard-0"
db = conn.getDB(conString);
db.auth("m121","aggregations")

When I run it I get the error

Error: couldn’t connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused

Could you please give me some advice on how to do this?

Thanks

The URI format is what you need. Suggest having a look at the connection string documentation.

1 Like

Also, read the documentation about the class Mongo. Without parameter it tries to connect to the default address and default port. That causes

Read the documentation of the method Mongo.getDB() you are supposed to provide the name of a database but you provide a connection string.

The connection string is probably the argument you need to pass to the Mongo contructor.

1 Like

https://docs.mongodb.com/manual/reference/method/js-connection/

1 Like