简体   繁体   English

如何在shell脚本中获取mongo数据库的确切集合列表

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

I would like to get the collection names list from mongo database. 我想从mongo数据库获取集合名称列表。 So, I use the following command in shell script : 因此,我在shell脚本中使用以下命令:

collections= mongo $dbName --eval "db.getCollectionNames()" 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" “ MongoDB Shell版本:2.2.0连接到:cm_v2 col1,col2,col3,col4”

I would like to get only the collections name such as : col,col2,col3,col4. 我只想获取集合名称,例如:col,col2,col3,col4。 So, how should I delete the output like version from result. 因此,如何从结果中删除类似版本的输出。

使用--quiet标志

collections=mongo $dbName --quiet --eval "db.getCollectionNames()"

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 这将返回带引号的JSON格式的名称列表,这对于BASH脚本并不是真正有用

mongo $dbName --quiet --eval "db.getCollectionNames()"

[
    "collection1",
    "collection2"
]

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

Batch version of Davor Lucic 's answer : 批处理版本的Davor Lucic答案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM