Ramavi
Ramavi

Reputation: 55

How to copy a record from one mongo collection to another mongo collection which are residing on different hosts which are accessible via ssh

I have two Mongo Instances on different hosts (dev & stage) which can be accessible via ssh.

How to copy a record from the collection on dev instance and insert it into the stage instance?

Steps tried:

Tried to use mongodump and mongorestore, but not of any use because my mongo instances are accessible via SSH.

Upvotes: 0

Views: 71

Answers (1)

mikezter
mikezter

Reputation: 2463

When using SSH, you can forward the MongoDB Ports to your local machine and use the usual MongoDB tools:

# first terminal
ssh -L27017:localhost:27017 mongohostA

# second terminal
ssh -L27018:localhost:27017 mongohostB

# third terminal
mongodump -h localhost -p 27017 ....
mongorestore -h localhost -p 27018 ....

What you are doing here is connect your local machines port 27017 to mongohostA MongoDB and your local machines port 27018 to mongohostB MongoDB. Then just use the MongoDB tools as usual, but configure different ports. Find documentation on those tools here: https://docs.mongodb.com/manual/reference/program/mongodump/

To have that working in a shellscript, we use auto closing SSH tunnels. In this example we also use the --query option to mongodump:

#!/bin/bash
ssh -f -L27017:localhost:27017 mongohostA sleep 10

mongodump -h localhost -p 27017 -d databaseName -c collectionName \
          --query '{"_id": yourSingleDocumentID }' ....

ssh -f -L27018:localhost:27017 mongohostB sleep 10

mongorestore -h localhost -p 27018 ....

Upvotes: 1

Related Questions