mongo shell script won't let me include "use <database>" - shell

32-bit mongo 2.0.1 on a windows XP machine
//script filename: test.js (one line shell script file to store a person)
db.cTest.save({Name: "Fred", Age:21});
run against database dbTest by entering the following 2 shell commands:
> use dbTest
switched to dbTest
> load("test.js")
So far, so good.
But if I try and include the "use" statement in the script it fails:
//script filename: test.js (including "use" statement)
use dbTest;
db.cTest.save({Name: "Fred", Age:21});
fails with error msg as follows:
> load("test.js")
SyntaxError: missing ; before statement
Mon Dec 19 11:56:31: Error: error loading js file temp.js (shell):1
Adding or removing semicolons to test.js doesn't seem to matter.
So how do you put a "use" directive into a mongo shell script?

In a mongo script you can use the db.getSiblingDB('new_db_name') to get a reference of a new database. So, it it not mandatory to give the database name in the command line. You can use the script.js:
db = db.getSiblingDB('new_db_name');
print(db);
// the rest of your code for database "new_db_name"
and the output of this script is (invoked with mongo script.js):
MongoDB shell version: 2.2.2
connecting to: test
sag

http://www.mongodb.org/display/DOCS/Scripting+the+shell
use dbname
This command does not work in scripted mode. Instead you will need to explicitly define the database in the connection (/dbname in the example above).
Alternately, you can also create a connection within the script:
db2 = connect("server:27017/otherdbname")

Well, it still is unfortunate that "load('file.js')" and "mongo file.js" don't actually use the same script interpreter as the interactive mongo shell. Opening the connection explicitly in the script is potentially a violation of the DRY principle because mongo already knows that information. What does work, though, is piping the file into mongo rather than passing its name on the command line:
mongo <file.js

Related

difference between execute shell script directly and through pipe

my shell script called mongoLogin.sh as below:
#!/bin/sh
mongo
use demo
show tables
the function of above is logining mongo and show tables of database called demo.
if I execute it directly by:
sh mongoLogin.sh
it works. however if I execute it by this way as below:
cat mongoLogin.sh | sh
compared with execute directly, it will exit automatically, as well as I ctrl+c after execute it directly. It seemed the sh command after pipe will create a new subprocess, and this subprocess finish due to some reason.
Do there exist some method that I can achieve same result by execute script through pipe?
update:
when execute directly it seemed only the first command make effect, because following commands are mongo operations rather than shell commands. And when I execute it by pipe, all commands make effect, but it exit automatically.
the output of executing it through pipe as below:
xxx#xxxMacBook-Pro:~/Downloads$cat mongoLogin.sh | sh
MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:27017
Implicit session: session { "id" : UUID("43c55950-f9e2-49ca-a458-
611f8c71eae4") }
MongoDB server version: 4.0.3
switched to db demo
test
bye
Both variants don't work, because use demo is not a valid shell command.
I have not worked with mongo, but if the command accepts is input from stdin, you can try
mongo <<OGNOM
use demo
show tables
OGNOM
Make sure that the final OGNOM starts in the first column of your line!

sqlplus does not execute the query if it is called by a ssh external connection

I have a script lying into a Unix server which looks like this:
mainScript.sh
#some stuff here
emailScript.sh $PARAM_1 $PARAM_2
#some other stuff here
As you can see, mainScript.sh is calling another script called emailScript.sh.
The emailScript.sh is supposed to perform a query via sqlplus, then parse the results and return them via email if any.
The interesting part of the code in emailScript.sh is this:
DB_SERVER=$1
USERNAME=$2
PASSWORD=$3
EVENT_DATE=$4
LIST_AUTHORIZED_USERS=$5
ENVID=$6
INTERESTED_PARTY=$7
RAW_LIST=$(echo "select distinct M_OS_USER from MX_USER_CONNECTION_DBF where M_EVENT_DATE >= to_date('$EVENT_DATE','DD-MM-YYYY') and M_OS_USER is not null and M_OS_USER not in $LIST_AUTHORIZED_USERS;" | sqlplus -s $USERNAME/$PASSWORD#$DB_SERVER)
As you can see, all I do is just creating the variable RAW_LIST executing a query with sqlplus.
The problem is the following:
If I call the script mainScript.sh via command line (PuTTy / KiTTy), the sqlplus command works fine and returns something.
If I call the script mainScript.sh via an external job (a ssh connection opened on the server via a Jenkins job), the sqlplus returns nothing and takes 0 seconds, meaning it doesn't even try to execute itself.
In order to debug, I've printed all the variables, the query itself in order to check if something wasn't properly set: everything is correctly set.
It really seems that the command sqlplus is not recognized, or something like this.
Would you please have any idea on how I can debug this? Where should I look the issue?
You need to consider few things here. While you are running the script, from which directory location you are executing the script? And while you are executing the script from your external application from which directory location it is executing the script. Better use full path to the script like /path/to/the/script/script.sh or use cd /path/to/the/script/ command to go to the script directory first and execute the script. Also check execute permission for your application. You as an user might have permission to execute the script or sql command but your application does not have that permission. Check the user id for your application and add that into the proper group.

sqlplus command not found zabbix

I'm working and discovering the world of Zabbix. In particular I am trying to monitor an Oracle database with the Zabbix server through an external script. Given that other external scripts work, however, I created one with sqlplus, but on Zabbix I get "command not found". Can you tell me why?
The code is:
check.pl
#!/usr/bin/perl
use strict;
use warnings;
my $out=`echo "select * from v$version;" | sqlplus user/password#ip_database:port`;
print $out;
The code is very simple.
I created an item as always, passed as type "external check" and a key I entered my script. Can anyone solve my problem? Also if I was not clear, just ask for more information rather than "insult" on the forum: Thanks to everyone in advance
I RESOLVED IT WITH:
echo "/usr/lib/oracle/11.2/client64/lib" > /etc/ld.so.conf.d/oracle.conf
echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/oracle/11.2/client64/lib" >> /etc/profile
THANKS TO ALL!!!!
Apparently, your zabbix server does not have the necessary environment to find sqlplus. You could simply use the full path to sqlplus in your script (but that alone might not be enough) or create a wrapper script that sets all the necessary environment variables for your script.
From TFM:
The command will be executed as the user Zabbix server runs as, so any
access permissions or environment variables should be handled in a
wrapper script, if necessary, and permissions on the command should
allow that user to execute it.
You also have to configure the sqlplus libraries required to run sqlplus. The script which you use to start the zabbix server you can configure below oracle things in the startup script so that zabbix can find all necessary libraries to run.
export ORACLE_HOME={path to Oracle Client}
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${ORACLE_HOME}/lib
If still there are issues related to .so files then there must be some issues in your SQL client installation.

Executing PSQL in R on Windows

I have been trying to execute PSQL from system() within R in RStudio. I have PSQL setup in my PATH and can execute PSQL from the cmd line. I cannot for the life of me figure out the correct method for executing psql from within R on windows. I have code supplied from a ubuntu environment. I have not used system() previously before this and researching for this specific issue has been unsuccessful.
The hardest part is not receiving any output after executing system in R. I have tried a few different setting from looking at ?system. With no luck.
This code should execute a simple sql statement and pass the output to a local file. Ultimately this will be more robust to include dynamic elements in an application. Just having the basics working seems like the hardest part.
system(paste("export PGPASSWORD=db_password;psql -h db_host -d db_name -c 'copy(select * from large_table limit 1000) to stdout csv' > C:/temp_data/db_test.dat", sep=""))
I am curious as to if anyone has a working windows environment using PSQL in R. My greenplum server is not local.
My echo %PATH% includes C:\Program Files (x86)\pgAdmin III\1.12
included in both system and user vars.
There are a few problems with your command.
system cannot be used with redirects, you must use shell
You cannot use single quotes to quote commands in Windows, you must use double quotes.
To concatenate commands, you use the & operator, not a ; like in Unix.
So your command would look like (it appears to be necessary to include this in one line):
cmd<-'set PGPASSWORD=db_password& psql -h db_host -d db_name -c "copy(select * from large_table limit 1000) TO STDOUT CSV;" > C:/temp_data/db_test.dat'
shell(cmd)
But, have you considered using the RPostgresql driver, which is a much simpler, platform-independent way to do your task?
# Load up the driver
library(RPGsql)
drv <- dbDriver("PostgreSQL")
# Create a connection
con <- dbConnect(drv, dbname="db_name", host='db_host',password='db_password',user='db_user')
# Query the database
db_test=dbGetQuery(con, 'select * from large_table limit 1000')
# Write your file
write.csv(db_test,'C:/temp_data/db_test.dat')

Mongo command line eval exits without error

I can't seem to .remove() from the command line. My query works fine if I go into the mongo shell, but not directly from bash.
$ mongo mydatabase --eval 'db.mytable.remove({expires: {$lt: Math.round(new Date().getTime() / 1000)}})'
MongoDB shell version: 2.0.6
connecting to: mydatabase
This command takes hours to run on all of our data when run manually through the mongo shell. It returns instantly without error from the bash shell like above.
I know there's data and can confirm it with a similar --eval:
$ mongo mydatabase --eval 'printjson(db.mytable.findOne({expires: {$lt: Math.round(new Date().getTime() / 1000)}}))'
MongoDB shell version: 2.0.6
connecting to: mydatabase
{
"_id" : "39e493ccef9d58bf75d856f55fb269f6",
"value" : "mydata",
"expires" : NumberLong(1371486135)
}
Any ideas why the db.mytable.remove() fails without error?
I've tried now with MongoDB shell version: 2.2.2 and it works fine:
mongo test --eval 'db.things.remove({expires: {$lt: Math.round(new Date().getTime() / 1000)}})'
Try to update MongoDB to a newer version if you are not already updated, plus I heard that latests mongoDB version use V8 Javascript engine could be useful
It's possible that in the shell, remove is not using getLastError, and is therefore asynchronous. If you fire off the command, you can check db.currentOp() to see if there are any commands running.
It's also possible that your query as given is being interpreted in the shell in such a way that it's not matching any records to delete. Make sure that a find returns data using that same query.
It's also possible that 2.0.6's shell uses the second justOne parameter by default, making it find and delete the first matching record, at which point it'll return. You might try passing an explicit second parameter false to force it to multi-record mode. I don't have a 2.0.6 shell to test with, but it's something to check for.

Resources