Unable to get run js from command to query mongodb - 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.

Related

How to remote connect to a mongo DB which sits on top of K8S

Currently I am working on a task to populate some data into a mongo DB. This mongo DB is built on top of K8S as follows. This is the first time I am working in such environment.
As you can see, on the "Shell" level, I was able to run
mongo -u root -p
to manually get into the mongo console page, and manually worked on the rest of DB queries.
But my question is, at the same "Shell" level, can I have all queries wrapped in a JS file and with a remote DB connection string to have it executed ?
Here is a sample of my read.js file I have tried:
var db = connect('127.0.0.1:27017/fext'),
allDevices = null;
allDevices = db.names.find();
//iterate the names collection and output each document
while (allDevices.hasNext()) {
printjson(allDevices.next());
}
And when I was to have it executed in this command:
mongo read.js -u root -p
I have got following returning message:
Comments ? Thanks for the help !
Jack

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/

How to copy part of a collection from a remote server to a local database in MongoDB

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

can't make basic mongo shell script with authentication

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.