Reputation: 547
I would like to get the collection names list from mongo database. So, I use the following command in shell script :
collections=mongo $dbName --eval "db.getCollectionNames()"
The output result of this command is
"MongoDB shell version: 2.2.0 connecting to: cm_v2 col1,col2,col3,col4"
I would like to get only the collections name such as : col,col2,col3,col4. So, how should I delete the output like version from result.
Upvotes: 2
Views: 6743
Reputation: 6930
Batch version of Davor Lucic's answer:
for /f "tokens=* usebackq" %%c in (
`echo show collections ^| mongo "host:port/dbname" --quiet`
) do (
echo %%c
)
Upvotes: 0
Reputation: 1416
use below:
DATABASE_COLLECTIONS=$(mongo $dbName --quiet --eval "db.getCollectionNames().join('')" | sed 's/,/ /g')
Then you can
for col in $DATABASE_COLLECTIONS; do
echo $col
done
Upvotes: 2
Reputation: 29420
If you want to get an array of collections that you can iterate over use something like this (this might bite you if you have spaces in collection names though):
collections=`echo "show collections" | mongo $dbName --quiet`
for collection in $collections;
do
echo "$collection"
done
This will return a JSON formatted list of names with quotes, which is not really useful for BASH script
mongo $dbName --quiet --eval "db.getCollectionNames()"
[
"collection1",
"collection2"
]
Upvotes: 5
Reputation: 43265
use --quiet
flag
collections=mongo $dbName --quiet --eval "db.getCollectionNames()"
Upvotes: 9