2013-07-25 3 views
0

나는 Mongodb에서 초보자입니다. 실제로 나는 다른 폴더에 수천 개의 파일이 있습니다. 모든 파일에는 json 데이터가 포함됩니다. 3 천만 개 이상의 파일이 있습니다. 그래서이 데이터를 저장하는 가장 좋은 방법은 문서 기반의 db라고 생각합니다.여러 JSON 파일을 Mongodb로 가져 오는 방법은 무엇입니까?

나는이Import more than 1 json file using mongoimport을 알고 있습니다. 그러나 허용 된 대답에는 파일 이름이 포함 된 모음이 필요합니다. 컬렉션에 30 수백만 파일 이름을 넣을 수 없습니다.

Windows env에서 여러 json 파일을 Mongodb로 가져올 수 있습니까?

답변

1

각 파일을 읽고, JSON으로 디코딩 한 다음 MongoDB에 하나씩 삽입하는 스크립트를 원하는 언어로 작성해야합니다. 당신은 특정 폴더에있는 모든 JSON 파일을 가져 오는 배치 스크립트를 만들 수 있습니다

<?php 
$f = glob("*.json"); 
$m = new MongoClient; 
$c = $m->myDb->myCollection; 

foreach ($f as $fileName) 
{ 
    $contents = json_decode(file_get_contents($fileName)); 
    $c->insert($contents); 
} 
?> 
0

다음 DB에 수입 :에 PHP, 이러한 스크립트는 유사한 것

@echo off 
for %%f in (*.json) do (
"mongoimport.exe" --jsonArray --db databasename --collection collectioname --file %%~nf.json) 

희망이 도와 드리겠습니다.

1

크로스 플랫폼 솔루션을 찾으려는 사람이라면 누구나이 작업을 수행 할 수있는 약간의 펄 스크립트를 만들었습니다. 데이터베이스와 디렉토리 인수를 취하고 디렉토리에서 찾은 .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"); 
     } 
    } 
} 
관련 문제