0

below is the bash script and I want to pass the value of 'a' from for loop to mongoDB command but I am getting $a is not defined error. How to pass the value to mongo command.

{ "account_id" : $a } is the part of the below command.

#!/usr/bin/bash

for a in `cat /tmp/account.txt`;
do
    mongo --authenticationDatabase admin -u 'xxxxxx' -p 'xxxxxxxxx' --quiet --eval 'db.executions.find({ $and : [  { "account_id" : $a }, { "status" : "running" }, { "created_at" : { "$gt" : ISODate("2022-09-01T00:00:00.000Z") } }, {  "created_at" : { "$lt" : ISODate("2022-10-01T00:00:00.000Z") } } ] } ,{"account_id":1,"created_at":1} ).count()' selfservice_production;
done

account.txt

35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
  • Maybe try swapping the single and double quotes per [this answer](https://stackoverflow.com/questions/840536/how-to-use-an-environment-variable-inside-a-quoted-string-in-bash) about environment variables in bash scripts? – user20042973 Sep 28 '22 at 16:31
  • tried swapping quotes but its not working. – Renu prashanth M Sep 28 '22 at 16:42
  • https://stackoverflow.com/questions/67379007/use-variables-with-eval-in-mongodb – R2D2 Sep 28 '22 at 17:46
  • Maybe instead of establish a connection for every single line you may also read the file in mongo shell (see [cat](https://www.mongodb.com/docs/v5.0/reference/method/cat/)) and process in the shell. Might be more efficient. – Wernfried Domscheit Sep 28 '22 at 20:23

1 Answers1

0

need to add the variable in single quotes. Its working for me.

{ "account_id" : "'$a'" } is what I changed.

#!/usr/bin/bash

for a in `cat /tmp/account.txt`
do
    mongo --authenticationDatabase admin -u "xxxx" -p "xxxxxxxxxx" --quiet selfservice_production --eval 'db.executions.find({ $and : [  { "account_id" : "'$a'" }, { "status" : "running" }, { "created_at" : { "$gt" : ISODate("2022-08-01T00:00:00.000Z") } }, {  "created_at" : { "$lt" : ISODate("2022-09-01T00:00:00.000Z") } } ] } ,{"account_id":1,"created_at":1} ).count()' 
done

Reference: Use variables with --eval in mongodb