Skip to content

Instantly share code, notes, and snippets.

@DiracSpace
Created August 26, 2023 23:41
Show Gist options
  • Save DiracSpace/29280285f1e4d071a166313464558b45 to your computer and use it in GitHub Desktop.
Save DiracSpace/29280285f1e4d071a166313464558b45 to your computer and use it in GitHub Desktop.
Script for importing multiple collections in JSON format into MongoDB using CLI
#! /bin/bash
find -- *.json | sed 's/.json$//' | while read -r col; do
echo "importing $col"
mongoimport -d edgraph -c "$col" --file "$col.json" --jsonArray
done
@DiracSpace
Copy link
Author

DiracSpace commented Sep 19, 2023

Run with the following:

curl -o- -L https://gist.githubusercontent.com/DiracSpace/29280285f1e4d071a166313464558b45/raw/f4f17a606573735cc00787b9a572a5d8b88a918b/import.sh | bash

@DiracSpace
Copy link
Author

Sometimes exporting a collection from MongoDB adds the database prefix into the name. So, if you want to obtain the collection name from the filename containing the prefix database_name.collection_name you can do the following:

# echo the filename property and pipe the result into cut command. 
# then obtain the second part of the text after the '.' character,
collection_name=$(echo $col | cut -d"." -f2)

echo "importing $collection_name"

# use that as a collection name during import 
mongoimport -d edgraph -c "$collection_name" --file "$col.json" --jsonArray

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment