2013-07-25 40 views
0

我是Mongodb的新手。其實我有成千上萬的文件在不同的文件夾中。所有文件都包含json數據。有超過三千萬個文件。所以我認爲存儲這些數據的最好方式是基於文檔的數據庫。我知道 Import more than 1 json file using mongoimport這個SO貼子。但是,接受的答案需要一個包含文件名的集合。我無法在一個集合中放入三千萬個文件名...如何將多個JSON文件導入Mongodb?

如何將多個json文件導入到Windows環境下的Mongodb?

回答

1

您需要用自己喜歡的語言編寫腳本來讀取每個文件,JSON將其解碼,然後將它們逐個插入到MongoDB中。在PHP中,這樣的腳本將類似於:

<?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

您可以創建一個批處理腳本獲取給定文件夾的所有JSON文件,然後導入到數據庫:

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

希望這幫助

1

對於任何尋找跨平臺解決方案的人,我創建了一個小Perl腳本來做到這一點。它需要一個數據庫和目錄參數,並將它在目錄中找到的任何.json文件導入到mongodb中。如果你不給它一個目錄,它只是使用你當前所在的那個目錄。我需要改進檢查.json文件的正則表達式,並且我相信這可以用更少的代碼來完成(I'一個新手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"); 
     } 
    } 
}