У меня проблема с поиском эффективного простого способа сохранить все индексы из пары БД.
У меня есть 2 решения. К сожалению, первый с db.system.indexes.find, который не поддерживается на всех серверах mongo (mongo 3.0+), а второй работает, но я верю, что он может быть улучшен:
1
for host in $mongo_host
do
for db in $(echo "db.getMongo().getDBNames()" | mongo --host ${mongo_host} | grep '"' | cut -d\" -f2)
do echo 'db.system.indexes.find({},{"key":1,"ns":1})' | mongo ${mongo_host}/${db} | grep ^[{] | sed 's/}$/, "host" : '"$mongo_host"'}/'
done
done | sort > $temp_index_file_path
2
echo "connecting to Mongo..."
for host in $mongo_host
do
#Get names of MongoDBs and save in array
my_array=($(echo "db.getMongo().getDBNames()"|mongo --host $mongo_host | grep '"' | cut -d\" -f2))
#Iterate over array of MongoDBs to gather collection names for next step
for i in "${my_array[@]}"
do
#Assign collections to temporary array using i from previous array to determine DB
temp_array=($(mongo $mongo_host/$i --eval "db.getCollectionNames()" | awk '/^\[/,/^\]/' | grep '"' | cut -d\" -f2))
#Iterate over array of MongoDBs collections to gather keys and names as last step
for j in "${temp_array[@]}"
do
#Gather keys and names from collecion $i stands for DB and $j for collection
if [ $j == "[object" ];then #dodgy element in collections
echo "skipping for $j collection"
continue
fi
n=$(echo $(mongo $mongo_host:$mongo_port/$i --eval "printjson(db.$j.getIndexes())"|sed -n '/key/,/}/p; /name/,/}/p '))
echo -e "element in $mongo_host Database $i Collection $j have index: $n \n\n" >> $temp_index_file_path
done
#clear temp array of collections
unset temp_array
done
done
На официальном сайте я нашел скрипт оболочки mongo
db.getCollectionNames().forEach(function(collection) {
indexes = db[collection].getIndexes();
print("Indexes for " + collection + ":");
printjson(indexes);
});
и попытался реализовать его в bash, но безуспешно:
for host in $mongo_host
do
for db in $(echo "db.getMongo().getDBNames()" | mongo --host ${mongo_host} | grep '"' | cut -d\" -f2)
do echo `db.getCollectionNames().forEach(function(collection) {
indexes = db[collection].getIndexes();
print("Indexes for " + collection + ":");
printjson(indexes) |sort > $temp_index_file_path
});`
done
done