How to get exact list of collections form mongo database in shell script

馋奶兔 提交于 2019-12-08 07:35:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!