JavaGeekGod
JavaGeekGod

Reputation: 1

Mongo shell to connect multiple hosts

is there a way to connect to two mongo hosts . Basically we have two mongo DBs in two separate servers. and we need to update data in the first one based on second. Is there a way we could do this

Upvotes: 0

Views: 1279

Answers (2)

Joe
Joe

Reputation: 28356

Yes, it is possible, but a lot of the pretty syntax in the mongo shell won't work, and the connect function doesn't seem to deal with replica sets, so you will need to find the primary yourself.

You can use the connect function to establish a connection to multiple servers, like:

var connection1 = connect("server1:27017")
var connection2 = connect("server2:27017")

But you won't be able to use the use or show commands or the rs object. Instead you will need to use the member functions and database commands.

For example, to list databases:

connection1.adminCommand("listDatabases")

To get a database reference:

var mydb = connection1.getSiblingDB("mydbname");
var otherdb = connection2.getSiblingDB("myotherdbname");

Find operations, etc, then look fairly normal:

mydb.collection.find({field: value});
otherdb.collection.insert({newfield: value});

Upvotes: 1

Igor Amelin
Igor Amelin

Reputation: 365

I think it's not possible to do this using mongo-shell. It can work with multiple instances of Mongo only if they are in one replica set.

You should create an application using Mongo-driver (e.g. mongoose for JS or MongoDB Driver for Java) that connects to your Mongos, and then implement updating your data how you need.

Upvotes: 0

Related Questions