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.
Related
In Java Driver of MongoDB, does it support reading mongo shell command directly? I am creating a Mongo client for Mongo dba in Java and want to allow users to type any kind of Mongo shell commands but I am not sure whether it is possible to do all dba tasks through Mongo Java Driver.
For example, when users type show dbs or show collections in mongo shell, a list of databases or collections will be shown. Also dba can type rs.status(), rs.config() commands to execute some admin tasks. I wonder whether mongo java driver supports that kind of input. I know I can use some API from the Java driver like database.runCommand(new Document(...)); but it needs some translating tasks between shell command and Java methods. Whether is there a better way to do that?
protected CommandResult runReplicaSetStatusCommand(final Mongo pMongo) {
// Check to see if this is a replica set... if not, get out of here.
final CommandResult result = pMongo.getDB("admin").command(
new BasicDBObject("replSetGetStatus", 1));
final String errorMsg = result.getErrorMessage();
if (errorMsg != null && errorMsg.indexOf("--replSet") != -1) {
System.err
.println("This is not a replica set - not testing secondary reads");
return null;
get full example at : http://massapi.com/source/bitbucket/12/14/1214103355/src/test/java/com/mongodb/util/TestCase.java.html#307
Hi I am trying to run a simple JavaScript program to retrieve data from mongodb. collection named news.
var doc=db.news.findone();
printjson(doc);
I have mongodb running in my machine. when I try to run it from my command prompt, I am getting the below result.
MongoDB shell version:2.4.15-pre-
connecting to: test
I have no idea why it is connecting to test. Someone please help.
I assume, the collection, "news" resides on some mongo logical database, which need to be specified in script. For exmaple
db = db.getSiblingDB('db_name')
doc = db.news.findOne()
printjson(doc)
Then evaluate the script using
mongo --host ${host} --port ${port} script.js
If you don't specify a database in your connection string like for example,
//Connect to foo
${host}:${port}/foo
mongo will always try to connect to "test" database.
I am new to MongoDB, so I'm probably just missing something simple. A remote server has a MongoDB database called DatabaseABC which has a collection called Logger. This collection is humongous. I figured the best way to understand how to query against it without having to wait several minutes between queries was to copy the last day's worth of documents in the collection locally.
From what I've read, I should be able to use cloneCollection and give it a query to filter it down. I can't get it to work. The documentation says,
You must connect directly to the mongod instance.
but I don't understand what that means. How do I connect to a local database using mongod? mongod seems like a way to start a database, I can do that, but I don't get how to run { cloneCollection: "DatabaseABC.Logger", from: "mongoDevEtc.domain.net:27017", query: { TheTimestamp: "2015-05-13" } } with it.
I need baby steps. Assume I have a local database called test. I have a fresh Microsoft Windows command prompt open pointed at the bin directory where mongod.exe exists. What commands do I enter in order to move all the logs written on May 13, 2015 from mongoDevEtc.domain.net:27017.DatabaseABC.Logger to my local collection at 127.0.0.1:21000.test.Logger (note, the logger collection doesn't exist locally yet)?
First of all mongod is the MongoDB server. It understands a bunch of different commands, but you need to use a client to issue those commands. The standard client for MongoDB is the Mongo Shell called mongo. You can invoke it directly from the command line and start issuing some commands.
Now, for your specific needs: the cloneCollection command allows you to copy from one collection in a DB on a distant server to an other collection, on a different DB on you local server (i.e.: the one to which your client is connected). From the Mongo Shell, you may issue this command (like any other "raw" command) using db.runCommand. Something like that:
> db.runCommand(
{ cloneCollection: "DatabaseABC.Logger",
from: "mongoDevEtc.domain.net:27017",
query: { TheTimestamp: "2015-05-13" }
}
)
Please note that is your distant db has the same name as your local db you might use the Mongo Shell database method db.cloneCollection instead:
> db.cloneCollection("mongoDevEtc.domain.net:27017",
"Logger",
{ TheTimestamp: "2015-05-13" })ΒΆ
As you can see below, db.cloneCollection is a simple wrapper around the cloneCollection database command:
> db.cloneCollection
function (from, collection, query) {
assert( isString(from) && from.length );
assert( isString(collection) && collection.length );
collection = this._name + "." + collection;
query = query || {};
return this._dbCommand( { cloneCollection:collection, from:from, query:query } );
}
To copy a database from a machine to your machine, fallow this steps:
Open the cmd
Run this code to copy:
mongodump --db Your_database_name /h IP_of_remote_machine
ex:
mongodump --db myDb /h 192.168.0.100
Run to restore the database from dump/myNpsCorporate to mongodb:
mongorestore --Your_database_name dump/Your_database_name
ex:
mongorestore --myDb dump/myDb
finish
I am running a Meteor app. locally using a Virtual Machine (VM). I want to use a new Mongo DB that I have set-up on the VM called 'my_db'. I have set the MONGO_URL on the command line like this:
export MONGO_URL='mongodb://127.0.0.1:3001/my-db'
I have checked that this environment variable is set using echo $MONGO_URL and I get back:
mongodb://127.0.0.1:3001/my-db
However, when I start up my Meteor app. it still connects to the default 'meteor' database. Why is this and what can I do to get it connecting to my alternative 'my_db' database?
Like #dr.dimitr say env vars are only used on the production process (for example connecting your modulus app with the modulus db they provide or another different), on the developing process you can use the mongo drive like this.
if(Meteor.isServer){
Meteor.startup(function () {
var myDatabase = new MongoInternals.RemoteCollectionDriver("<mongo url>");
MyCollection = new Mongo.Collection("collection_name", { _driver: myDatabase });
});
}
Now you need to know name of the url <mongo url> which could be something like mongodb://127.0.0.1:27017/local or meteor
Some Related Posts - (1) and (2)
I am trying to connect to my Mongo database which is situated on the machine as my Meteor app. Here are two files in my app:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js:
if (Meteor.isClient) {
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}
But I keep getting a "Exception in template helper: ReferenceError: Boxes is not defined" error - any ideas?
How can you connect to a MongoDB with Meteor?
Scenario A: Use the built-in DB as default
This is much simpler than what you did. When you run meteor you actually start a DB with the Meteor server, where Meteor listens on port 3000 and the database on port 3001. The Meteor app is already connected to this database at port 3001 and uses a db named meteor. There is no need whatsoever to fall back to MongoInternals.RemoteCollectionDriver. Just remove that code and change things to:
Boxes = new Mongo.Collection("boxes"); // use default MongoDB connection
Scenario B: Use a different DB as default
Using the MONGO_URL environment variable you can set the connection string to a MongoDB when starting the Meteor server. Instead of the local port 3001 database or an unauthenticated connection you can specify exactly where and how to connect. Start your Meteor server like this:
$ MONGO_URL=mongodb://user:password#localhost:27017/meteor meteor
You can also leave out the user:password# part of the command if no authentication is needed.
Scenario C: Connect to a second (3rd, etc) DB from the same Meteor app
Now we need to use MongoInternals.RemoteCollectionDriver. If you wish to use another database that is not the default DB defined upon starting the Meteor server you should use your approach.
var database = new MongoInternals.RemoteCollectionDriver('mongodb://user:password#localhost:27017/meteor');
var numberOfDocs = database.open('boxes').find().count();
Bonus: Why should you not use MongoInternals with Mongo.Collection?
As the docs indicate you should not pass any Mongo connection to the new Mongo.Collection() command, but only a connection to another Meteor instance. That means, if you use DDP.connect to connect to a different server you can use your code - but you shouldn't mix the MongoInternals with Mongo.Collection - they don't work well together.
Based on feedback from saimeunt in the comments above, s/he pointed out that MongoInternals is unavailable to the client portion of a Meteor app. Therefore, the solution was to add in the line "Boxes = new Mongo.Collection("boxes");" to the client logic - here was the final working solution:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js
if (Meteor.isClient) {
Boxes = new Mongo.Collection("boxes");
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}
Meteor has 2 different environment : the server environment running on Node.JS and the client environment running in browsers.
In your code you declare the Boxes Mongo collection only in the server environment, you need to take this declaration out of the Meteor.isServer condition (and BTW don't use these, separate your code in server/, client/ and lib/ directories).
Also, not sure if you need to connect to your MongoDB this way, maybe you should look into the MONGO_URL environment variable it probably already does what you need ? (provide a mongo connection URL to a distant (or local) Mongo server).