크로스 플랫폼 솔루션을 찾으려는 사람이라면 누구나이 작업을 수행 할 수있는 약간의 펄 스크립트를 만들었습니다. 데이터베이스와 디렉토리 인수를 취하고 디렉토리에서 찾은 .json 파일을 mongodb로 가져옵니다. 만약 당신이 디렉토리를주지 않는다면, 현재 사용중인 파일을 사용합니다. .json 파일을 검사하는 정규 표현식을 수정해야합니다. 그리고이 코드는 적은 코드로 처리 할 수있을 것이라고 확신합니다. m 초보자 Perl 수도사) 그러나 이것은 작동하고 나는 Perl를 좋아한다. 그래서, 이것을 발견하는 누군가에게 - 즐기십시오.
#!/usr/bin/perl
use strict;
use warnings;
#this is a script for enumerating over every json file in a folder and importing it into mongodb
my ($database, $directoryPath) = @ARGV;
if(! $database) { #check for required database argument
die "A database argument must be provided to the script. Ex: perl mongorestore.pl wasp";
}
#if a directory path is not given in arguments, operate in the current directory.
if(!$directoryPath) {
$directoryPath = '.';
}
#open directory and import json files to mongo
opendir my $dir, $directoryPath or die "Cannot open directory at path $directoryPath.";
my @files = readdir $dir;
importJSONToMongo(@files);
closedir $dir;
#subroutine that takes an array of json files and imports them to the given mongodb database
sub importJSONToMongo {
foreach my $file (@_) {
if($file =~ /.json/) { #only import json files - need to make this regex better (it would match *.metadata.json and other extraneous files)
$file =~ /(^.+?)(?=\.)/; #capture the filename before the '.json' extension
system("mongoimport -d $database -c $1 --jsonArray --file $directoryPath/$1.json");
}
}
}