2

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.

4 Answers 4

9

use --quiet flag

collections=mongo $dbName --quiet --eval "db.getCollectionNames()"
Sign up to request clarification or add additional context in comments.

Comments

5

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"
]

Comments

2

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

Comments

0

Batch version of Davor Lucic's answer:

for /f "tokens=* usebackq" %%c in (
  `echo show collections ^| mongo "host:port/dbname" --quiet`
) do (
  echo %%c
)

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.