I am working on a bash script and would like to have a for loop iterate over specific collections in mongo and perform a count. If any of these specific collections is non-zero, then break the loop.
I have initialize this variable inside my script (assume the connection is working):
MONGO_EVAL="mongo prod $MONGO_CONN_CONF --quiet --eval"
and also a list for specific collections (initialized above, at an early phase in the script):
db_collections=(collectionA collectionB collectionC....)
Then iterate over a for loop and count the documents on each collection.
for str in ${db_collections[@]}; do
$MONGO_EVAL 'db.$db_collections.count();'
done
How do I do it the right way?
CodePudding user response:
Should be rather this:
db_collections=(collectionA collectionB collectionC....)
for str in ${db_collections[@]}; do
mongo "$MONGO_CONN_CONF" --quiet --eval "db.${str}.count();"
done
or
for str in ${db_collections[@]}; do
mongo "$MONGO_CONN_CONF" --quiet --eval "db.getCollection('${str}').count();"
done
or
mongo "$MONGO_CONN_CONF" --quiet --eval "for (let c of ['collectionA', 'collectionB', 'collectionC']) db.getCollection(c).count();"
Note, you have to use double quotes ("
), otherwise ${str}
is not replaced by variable value.
Regarding your actual problem "If any of these specific collections is non-zero, then break the loop" if could be like this:
for (let c of ['collectionA', 'collectionB', 'collectionC']) {
let count = db.getCollection(c).count();
if (count > 0) break;
}
Bear in mind, this loop actually does nothing, just count and potentially exit. I assume you would also need at least a print(c)
or something similar.