You've already forked mongo-index-helper
58 lines
1.4 KiB
Bash
Executable File
58 lines
1.4 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
|
|
usage() {
|
|
echo "Usage: $0 --uri <uri> --db <dbname> --output <file>"
|
|
echo ""
|
|
echo " --uri MongoDB connection URI (e.g. mongodb://user:pass@host:27017/admin)"
|
|
echo " --db Database name"
|
|
echo " --output Path to output JSON file"
|
|
exit 1
|
|
}
|
|
|
|
URI=""
|
|
DB=""
|
|
OUTPUT=""
|
|
|
|
while [[ $# -gt 0 ]]; do
|
|
case "$1" in
|
|
--uri) URI="$2"; shift 2 ;;
|
|
--db) DB="$2"; shift 2 ;;
|
|
--output) OUTPUT="$2"; shift 2 ;;
|
|
*) echo "Unknown argument: $1"; usage ;;
|
|
esac
|
|
done
|
|
|
|
[[ -z "$URI" ]] && echo "Error: --uri is required" && usage
|
|
[[ -z "$DB" ]] && echo "Error: --db is required" && usage
|
|
[[ -z "$OUTPUT" ]] && echo "Error: --output is required" && usage
|
|
|
|
TMP_JS=$(mktemp /tmp/mongo-export-XXXXXX.js)
|
|
trap 'rm -f "$TMP_JS"' EXIT
|
|
|
|
cat > "$TMP_JS" <<'EOF'
|
|
const dbName = process.env.MONGO_DB;
|
|
const targetDb = db.getSiblingDB(dbName);
|
|
|
|
const result = {};
|
|
const collections = targetDb.getCollectionNames();
|
|
|
|
for (const collName of collections) {
|
|
const indexes = targetDb.getCollection(collName).getIndexes();
|
|
const filtered = indexes.filter(idx => idx.name !== "_id_");
|
|
|
|
if (filtered.length > 0) {
|
|
result[collName] = filtered.map(idx => {
|
|
const { v, ns, ...rest } = idx;
|
|
return rest;
|
|
});
|
|
}
|
|
}
|
|
|
|
print(JSON.stringify(result, null, 2));
|
|
EOF
|
|
|
|
MONGO_DB="$DB" mongosh --quiet "$URI" --file "$TMP_JS" > "$OUTPUT"
|
|
|
|
echo "Exported indexes to: $OUTPUT"
|