-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongoexport.sh
62 lines (52 loc) · 1.88 KB
/
mongoexport.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/bin/bash
set -e
# Declare connection variable
dbname=$DBNAME
username=$USERNAME
password=$PASSWORD
host=$HOST
idValue=$ID
keyField=$KEY
bucket=$BUCKET
aws_access_key_id=$AWSACCESSKEYID
aws_secret_access_key=$AWSSECRETACCESSKEY
mongo --quiet "mongodb+srv://$username:$password@$host/$dbname" --eval "db.stats();"
RESULT=$? # returns 0 if mongo eval succeeds
if [ $RESULT -ne 0 ]; then
echo "Can't connect to MongoDB server"
exit 1
break
else
collections=$(mongo --quiet "mongodb+srv://$username:$password@$host/$dbname" --eval 'rs.slaveOk();db.getCollectionNames().join(" ");' | tail -1)
IFS=', ' read -r -a collectionArray <<<"$collections"
echo "Connected to $host @ $dbname with $username"
echo " "
exportDate=$(date -Iseconds)
aws configure set aws_access_key_id $aws_access_key_id
aws configure set aws_secret_access_key $aws_secret_access_key
fi
while true; do
unset idValue
unset keyField
if [ -z "$keyField" ]; then
echo "Enter Field to export (tenant, organization, group, etc.):"
read keyField
fi
if [ -z "$idValue" ]; then
echo "Enter ID value to export:"
read idValue
fi
mkdir -p $PWD/$idValue/$exportDate
for ((i = 0; i < ${#collectionArray[@]}; ++i)); do
echo "Exporting $idValue from collection ${collectionArray[$i]}"
mongoexport --uri="mongodb+srv://$username:$password@$host/$dbname" --collection ${collectionArray[$i]} --query="{\"$keyField\": {\"\$oid\": \"$idValue\"}}" --out $PWD/$idValue/$exportDate/${collectionArray[$i]}.json
aws s3 cp $PWD/$idValue/$exportDate/${collectionArray[$i]}.json s3://$bucket/$idValue/$exportDate/${collectionArray[$i]}.json
echo "${collectionArray[$i]} collection exported."
done
echo "Done. All collections have been exported here s3://$bucket/$idValue/$exportDate/"
echo "Export another value of $keyField? [y/n] :"
read response
if [ "$response" != "y" ]; then
break
fi
done