MongoDB run query from terminal - bash

I'm try run bash script from terminal (Ubuntu 14.04), but i'm get error:
$ ../scripts/for_webapp/init_devices_limit.sh
db.company.update({"_id": NumberInt(777)}, {$set: {"devices_limit": NumberInt(-1)}}, {"multi":true});
MongoDB shell version: 3.2.5
connecting to: localhost:27017/statistic
2016-04-22T12:37:01.366+0500 E QUERY [thread1] SyntaxError: expected expression, got end of script #(shell eval):1:25
Script:
#!/usr/bin/env bash
: ${DBHOST:=localhost}
: ${DBPORT:=27017}
: ${DBNAME:=statistic}
: ${COMPANY_ID:=777}
: ${INIT_VALUE:=-1}
QUERY='db.company.update({"_id": NumberInt('$COMPANY_ID')}, {$set: {"devices_limit": NumberInt('$INIT_VALUE')}}, {"multi":true});'
echo $QUERY
mongo $DBHOST:$DBPORT/$DBNAME --eval $QUERY

I'm solve this with using EOF input signal (without use --eval argument).
#!/usr/bin/env bash
: ${DBHOST:=localhost}
: ${DBPORT:=27017}
: ${DBNAME:=statistic}
: ${COMPANY_ID:=777}
: ${INIT_VALUE:=-1}
QUERY='db.company.update({"_id": NumberInt('$COMPANY_ID')}, {$set: {"devices_limit": NumberInt('$INIT_VALUE')}})'
echo $QUERY
# mongo $DBHOST:$DBPORT/$DBNAME --eval $QUERY
# don't use --eval
mongo $DBHOST:$DBPORT/$DBNAME <<_EOF_
$QUERY
_EOF_

Related

single quote issue if i use function in bash [duplicate]

This question already has answers here:
When to wrap quotes around a shell variable?
(5 answers)
Closed 11 months ago.
I have a script like below and I am running queries in mongodb. But when I call it as a function, it adds single quote and my query doesn't work. How can i solve this problem?
My Code:
mongo_func() {
mongo "$MONGO/$1" --quiet --eval $2 $3 $4
}
mongo_func "Users" 'db.ucol.updateMany({}, { $unset : {"name" : "", "Users": ""}});'
When I debug with bash -x, the output looks like below.
mongo 10.10.1.2/Users --quiet --eval 'db.ucol.updateMany({},' '{$unset:' '{"name"' : '"",' '"Users":' '""}});'
It s working as follows properly.
mongo 10.10.1.2/Users --quiet --eval 'db.ucol.updateMany({}, {$unset: {"name" : "", "Users": ""}});'
That's because you have failed to quote the function arguments.
Try this instead.
mongo_func() {
user=$1
shift
mongo "$MONGO/$user" --quiet --eval "$#"
}

How do I create a .bash_profile alias for a GroupMe bot's message command

I have a GroupMe bot that can send messages to the chat it is assigned to in this format:
curl -d '{"text" : "text", "bot_id" : "(REDACTED)"}' https://api.groupme.com/v3/bots/post
So, instead of typing up this monstrosity every time I wanted to send a message, I decided to create an alias for it.
Here is what I attempted to use in my .bash_profile for this:
alias groupmessage=groupmessagefunction
groupmessagefunction() { curl -d '{"text" : $1, "bot_id" : "(REDACTED)"}' https://api.groupme.com/v3/bots/post; }
Could anyone inform me what the correct formatting would be to get this to work? Thanks!
Update 1:
I now have my code as follows:
v="bot_id_string"
alias groupmessage=groupmessagefunction
groupmessagefunction() { curl -d '{"text" : '"$1"', "bot_id" : '"$v"'}' https://api.groupme.com/v3/bots/post; }
I would like to point out that what I am trying to accomplish is type in something like:
groupmessage "hello"
or
groupmessage hello
Then, it will send out the following command:
curl -d '{"text" : "hello", "bot_id" : "bot_id_string"}' https://api.groupme.com/v3/bots/post
I hope this helps clarify this question if any misunderstanding occurred.
Now, I hope this will be the solution for you:
v=bot_id
curl -d '{"text" : "Test", "'$v'" : "(REDACTED)"}' api.groupme.com/v3/bots/post
You have to use ' ' around $v --> '$v' because this will allow bash to evaluate $v inside curl -d ' ... ' .
Answer for your Update 1
As I see it would be the better way to use eval command:
v="bot_id_string"
alias groupmessage=groupmessagefunction
groupmessagefunction() {
a="curl -d '{\"text\" : \"$1\", \"bot_id\" : \"$v\"}' https://api.groupme.com/v3/bots/post"
echo "$a" # this echo just for checking
eval "$a"; }
groupmessage "Hello is it working now ?"

How can I insert a document from a bash script to mongodb?

What is the exact code I need to execute, to insert a document into a mongodb using bash. At the moment I am able to look documents in mongodb via bash script up, but inserting does not work.
You can inject javascript code from a javascript file:
mongo 127.0.0.1/MyDatabase script.js
with script.js:
var document = {
name : "document_name",
title : "document_title"
};
db.MyCollection.insert(document);
or directly:
mongo 127.0.0.1/MyDatabase --eval 'var document = { name : "document_name", title : "document_title" }; db.MyCollection.insert(document);'
If you don't want to serve script from a file (I try not to source external files as much as possible) or not use --eval option which can be difficult to read if you have many entries, you can use a bash heredoc
You can type in terminal:
-bash-4.1$ mongo mongodb://myServerAddress/myDbName <<EOF
> db.myCollectionName.insert({
> name: "doc name",
> title: "doc title"
> })
> EOF
Result:
MongoDB shell version v3.4.1
connecting to: mongodb://myServerAddress/myDbName
MongoDB server version: 3.0.7
WARNING: shell and server versions do not match
WriteResult({ "nInserted" : 1 })
bye
-bash-4.1$
If you want to keep it in a script, just remove > which is actually prompt for a multiline command.
For in-script use, it should be as below:
#!/usr/bin/env bash
mongo mongodb://myServerAddress/myDbName <<EOF
db.myCollectionName.insert({
name: "doc name",
title: "doc title"
})
EOF
insert some JSON into Mongo DB sample_db, collection products_coll
echo '{ item: "card", qty: 115 }' | \
sed 's#^#db.products_coll.insert( #; s#$# ) #' | mongo sample_db
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017/sample_db
MongoDB server version: 3.6.3
WriteResult({ "nInserted" : 1 })
bye
make sure it is here
mongoexport -d sample_db -c products_coll
{"_id":{"$oid":"5d27e83152a049227799710e"},"item":"card","qty":115.0}

not foundsh: 2: error comes while exectutin a shell command?

when i run sh backuptest.sh, following error comes .So is it issue with the code or my shell
result :
: not foundsh: 2: backuptest.sh:
: not foundsh: 4: backuptest.sh:
: not foundsh: 6: backuptest.sh:
: not foundsh: 7: backuptest.sh:
content of backuptest.sh
#!/bin/sh -e
location=`date +%Y%m%d`.sql
mysqldump -u root -proot spider_db > $location
remove #!/bin/sh -e and try
dos2unix backuptest.sh
then execute again with
./backuptest.sh

Execute psql query in bash

I have a problem with executing a psql-query in a bash script.
Below is my code.
run_sql(){
sql_sel="$1;";#sql select
table=$2;#table name
for i in "${!GP_SERVER_NAMES[#]}"
do
logmsg "Executing [$sql_sel] on "${GP_SERVER_NAMES[$i]}": " $loglvl;
result_host[$i]=`${PSQL_HOST[$i]}${sql_sel}`;
#result_host[$i]=cleanresult "`$(${PSQL_HOST[$i]} "$tx_fix $sql_sel" 2>&1`");
if [[ `checkresult "${result_host[$i]}"` != 'true' ]]; then
logmsg "Error occured during sql select: Result for "${GP_SERVER_NAMES[$i]}" '${table}': ${result_host[$i]};" '1' '1';
raise_alarm "${GP_SYNC_SQL_ERR}" "${i}" "${table}" "${result_host}";
fi
logmsg "Result for" ${GP_SERVER_NAMES[$i]} " '${table}': ${result_host[$i]}";
done
final_result='true';
for i in "${!result_host[#]}"
do
if [[ `checkresult "${result_host[$i]}"` = 'true' ]]; then
final_result='false';
I am trying to executing the query on many different servers, with the following command
result_host[$i]=${PSQL_HOST[$i]}${sql_sel};
The above variables have the following meaning:
1. result_host[$i] : is an array that holds the i-th result of the sql query.
2. PSQL_HOST[$i] : is the command line psql-statement, including the IP address which is of the form
psql -t -q -h -U password -d database -c
3. $sql_sel : is the sql_statement
When I run the script, I get the following output.
scriptname.sh: line 168: SELECT: command not found
ERROR: syntax error at end of input
LINE 1: SELECT
^
Why is that? Any help, comments or suggestions would be appreciated.

Resources