问题
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.
回答1:
use --quiet flag
collections=mongo $dbName --quiet --eval "db.getCollectionNames()"
回答2:
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"
]
回答3:
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
回答4:
Batch version of Davor Lucic's answer:
for /f "tokens=* usebackq" %%c in (
`echo show collections ^| mongo "host:port/dbname" --quiet`
) do (
echo %%c
)
来源:https://stackoverflow.com/questions/21038710/how-to-get-exact-list-of-collections-form-mongo-database-in-shell-script