This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
# copyIndexes.sh | |
# @description Copies indexes from one mongodb database to another | |
# @author Nestor Urquiza | |
# @date 20230530 | |
USAGE='Usage: copyIndexes.sh --user1 <user1> --host1 <host1> --db1 <db1> --user2 <user2> --host2 <host2> --db2 <db2>' | |
# options | |
while [[ $# -gt 1 ]]; do | |
key="$1" | |
case $key in | |
--user1) | |
user1="$2" | |
shift | |
;; | |
--host1) | |
host1="$2" | |
shift | |
;; | |
--db1) | |
db1="$2" | |
shift | |
;; | |
--user2) | |
user2="$2" | |
shift | |
;; | |
--host2) | |
host2="$2" | |
shift | |
;; | |
--db2) | |
db2="$2" | |
shift | |
;; | |
*) | |
# unknown | |
;; | |
esac | |
shift | |
done | |
if [[ "$user1" == "" || "$host1" == "" || "$db1" == "" || "$user2" == "" || "$host2" == "" || "$db2" == "" ]]; then | |
echo $USAGE | |
exit 1 | |
fi | |
# Retrieve indexes from host1 | |
echo "Copying indexes *FROM* $host1/$db1 using user $user1 ..." | |
indexes=$(mongo "$host1/$db1" -u $user1 -p --quiet --eval 'JSON.stringify(db.getCollectionNames().map(function(collectionName) { return {collection: collectionName, indexes: db.getCollection(collectionName).getIndexes()}; }))') | |
# Connect to host2 and import indexes | |
echo "Copying indexes *TO* $host2/$db2 using user $user2 ..." | |
mongo "$host2/$db2" -u $user2 -p --quiet --eval ' | |
var indexData = '$indexes'; | |
indexData.forEach(function(indexInfo) { | |
var collectionName = indexInfo.collection; | |
var indexes = indexInfo.indexes; | |
indexes.forEach(function(index) { | |
db.getCollection(collectionName).createIndex(index.key, index.options); | |
}); | |
}); | |
' | |
echo "Indexes have been copied successfully from $host1/$db1 to $host2/$db2." |