简体   繁体   中英

Connect to replica set within mongo shell

I'm trying to write a Mongo shell script that connects to two databases, searches for some document(s) in one, and inserts the found document(s) into the other. Kinda like this:

#!/bin/sh
mongo --shell --nodb <<EOF
var db1 = new Mongo( '...' );
var db2 = new Mongo( '...' );
db1.collection.findOne( {...} ).forEach( function( r ) { 
  db2.collection.save( r ) 
});

The trick is, both databases are replica sets, and require a username and password.

What is the syntax for using new Mongo() to connect to a replica set and authenticating as a particular user? I tried to use a Mongo URI ( http://docs.mongodb.org/manual/reference/connection-string/ ) but that didn't work.

I don't have a replica set to test this on but I think you can use the Mongo() constructor like this

conn = Mongo("replicasetname/host:port")

from there I think you'll need to get the database manually with

db = conn.getDB("myDatabase")

and then authenticate

db.auth(user, pass)

This could all depend on what shell version you're using as well. I don't see any documentation on using the replica set connection in the latest version so I don't know if it's deprecated or just not mentioned anymore. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM