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
4
  • Maybe try swapping the single and double quotes per this answer about environment variables in bash scripts? Commented Sep 28, 2022 at 16:31
  • tried swapping quotes but its not working. Commented Sep 28, 2022 at 16:42
  • stackoverflow.com/questions/67379007/… Commented Sep 28, 2022 at 17:46
  • Maybe instead of establish a connection for every single line you may also read the file in mongo shell (see cat) and process in the shell. Might be more efficient. Commented Sep 28, 2022 at 20:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.