can't make basic mongo shell script with authentication - mongodb

I have a really complicated issue that i think i can solve by writing a mongo shell script but i can't even manage to make a simple connection. I have a local mongo database which is requires a username/password that i normally access like this:
mongo admin -u <username> -p
at which point I enter the password and hooray! i have a shell. but that won't work for my issue. As a test, I created a file called test.js and all it has in it is this:
var conn = new Mongo()
db = conn.getDB("test");
db.cust.find();
I then run the script from the command line like so:
mongo test.js
at which point i get this:
MongoDB shell version: 2.4.10
connecting to: test
Why am i getting no results?

I finally made this work. This is how i ended up doing it:
First I made a file called test.js with the following in it:
db = connect("localhost:27017/admin");
db.auth('username','password');
db = db.getSiblingDB('test');
var cursor = db.cust.find();
while (cursor.hasNext()) {
printjson(cursor.next());
}
I then ran this command from the command line:
mongo test.js
I also want to point out a few things that i learned while trying to do this to any other developer who is having issues.
1) if you add a new database, and your are running mongo with authentication you either need to log into the authentication database first and then switch to the desired database (as my example shows) or you need to add a user/password to the desired database (as i probably should have done in the first place)
2) When running a javascript file via mongo, don't expect to use the same "javascript" functions that you are used to. I just learned a hard lesson that not all javascript is the same. for example, you can not use Console.log() in a javascript file that is run via mongo because console.log is not actually core javascript but rather a function specific to browser and node implementations.

Related

How do I set the default connection URL for mongo CLI?

I cannot find anywhere to set the default connection URL for the mongo CLI. I want to be able to specify a particular username/password/hostname/database, which can all be specified as a URL. However, I want to just be able to type mongo instead of mongo "mongodb://…" in the shell.
I also don’t want the password to show up in /proc/«PID»/cmdline, but having it in a dotfile in my home directory is perfectly fine with me.
It doesn’t appear that ~/.mongorc.js allows specifying the default connection string. But I would expect such an option to be available because the mysql CLI supports ~/.my.cnf which allows you to specify username/password/hostname/database. So, where is this for mongodb?
EDIT: The solution has to work even if the mongodb at localhost is fully secured (no insecure local test database should be required—I thought this went without saying).
You can run mongo shell commands in ~/.mongorc.js. So you can just run the connect method in your ~/.mongorc.js:
db = connect("mongodb://username:password#host:27017/myDatabase")
When you run mongo it will first connect to localhost, then connect to the database passed to the connect method.
A MongoDB server must be running on localhost, otherwise the mongo shell will error and exit before trying to connect to the other DB.
Run mongo --nodb to get around needing to connect on localhost before connecting to whatever is defined in ~/.mongorc.js.
To directly launch mongo against a particular hostname/database/username/password without prompting for a password, without passing the password on the CLI, and without requiring an insecure database at mongodb://localhost/test, you can use this technique. Write a script file which does the connection for you and then launch mongo with the appropriate arguments. For example:
~/.mongo-do-auth.js
// https://docs.mongodb.com/manual/reference/program/mongo/#cmdoption-nodb
// https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#mongo-shell-new-connections
//
// Run this with:
//
// mongo --nodb --shell ~/.mongo-do-auth.js
db = connect('localhost/admin', 'root', 'asdf123');
And then, simply launch it from the CLI to get an interactive session:
sam ~ # mongo --nodb --shell ~/.mongo-do-auth.js
MongoDB shell version: 2.6.12
type "help" for help
connecting to: localhost/admin
> quit()
Or, to run a script noninteractively, simply remove --shell and append your script. Consider a script:
s2.js:
print('connected to database ' + db);
To run:
sam ~ # mongo --nodb ~/.mongo-do-auth.js ~/s2.js
MongoDB shell version: 2.6.12
loading file: /root/.mongo-do-auth.js
connecting to: localhost/admin
loading file: /root/s2.js
connected to database admin
However, this requires a lot of work and invoking mongo with arguments. It appears that this is a limitation of mongo because no one has suggested any alternative which works as smoothly as the mysql CLI client’s ~/.my.cnf. This means that all shell scripts which directly invoke mongo will need to allow the the user to pass through --nodb and a path to a connection script instead of being able to rely on implicit per-user configuration.

MongoDB and Batch script operation

I am trying to run MongoDB queries from batch script in windows...
I can not find any reference how to do that. Please can you show me some sample commands and one more question.
I am running this command for changing the database...
mongo --eval "use Sample_Test"
It does not work.
when I am inserting some data. It works, but, inserts in the default database, test.
mongo --eval "db.restaurants.insert({'Name':'Vishal'})"
I want to insert data in Sample_Test Database.
I only know above "mongo --eval" command, if anybody knows some more, please share it.....it would really help.
The data is getting inserted to default database as your use DB is not working here.
You need to add database name here using -d if you are using older version of MongoDB like following :
mongo -d Sample_Test --eval "db.restaurants.insert({'Name':'Vishal'})"
or you can execute any script file which contains all your mongo script like following:
mongo -d Sample_Test --eval mongoScript.js
In Mongo version 3.2, -d flag is not needed. For more information about script refer documentation
So you can simply use
mongo Sample_Test --eval "db.restaurants.insert({'Name':'Vishal'})"
Hope this will work for you.
use this code on place of your code:
mongo.exe Sample_Test --eval "db.restaurants.insert({'Name':'Vishal'})"
but if you want to run multiple commands in one session login use script file.
You can also use the URL style to connect to a MongoDb server and database like:
mongo "mongoldb://localhost:8000/myCars" --eval "db.getCollection('restaurants').insert({'Name':'Vishal'})
You can also put credentials into the URL.
See: https://docs.mongodb.com/manual/mongo/

Unable to get run js from command to query mongodb

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.

How to query MongoDB without switching to the database first

When I connect to MongoDB from the command-line using the mongo command, I need to issue a use <db> command to switch to the appropriate database before I can run a query, like this:
[mongo#mongotest ~] $ mongo localhost:10001
MongoDB shell version: 2.4.6
connecting to: localhost:10001/test
> use mydb01
switched to db mydb01
Now I can run my query:
> db.records.find({"contact.name": "Jack"});
Is there a way to consolidate those commands into a single command? For example:
> mydb01.records.find({"contact.name": "Jack"});
The MongoDB shell documentation makes it seem like there should be a way, but I haven't been able to find it.
You can get a database object of another database than the one your are useing right now with db.getSiblingDB.
> db.getSiblingDB("mydb01").records.find({"contact.name": "Jack"});
You can also store that object in a variable. That way you can easily work with many databases simultaneously.
> var mydb01 = db.getSiblingDB("mydb01");
> mydb01.records.find({"contact.name": "Jack"});

When using a separate MongoDB with meteor, meteor reset stopped working

I have my MONGO_URL set to mongodb://localhost:27017/meteor and have the MongoDB run as a service.
When running my project it seems OK to store data to the separate MongoDB until I tried to run meteor reset.
My assumption is it tried to remove its default database. The error complained that myproject.meteor\local is not empty and pointed to fs.js:456 which goes to files.js:256 (rm_recursive) and so on.
any idea what and how I can fix this?
$ meteor reset only resets the bundled MongoDB. It won't reset an external Mongo database.
(That's something we should explain better in the documentation.)
In your case, try connecting to the Mongo database directly (with the mongo command line shell) and running > db.dropDatabase()